CSS盒子模型居中方法
文章目录
方法一:
利用margin;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>demo</title>
</head>
<body>
<style type="text/css">
.div1{
width: 100px;
height: 100px;
border: 1px solid #000000;
}
.div2{
width:40px ;
height: 40px;
background-color: green;
}
.div22{
margin-left: 30px;
margin-top: 30px;
}
</style>
<div class="div1">
<div class="div2 div22">
</div>
</div>
</body>
</html>方法二
利用css的 position属性;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>demo</title>
</head>
<body>
<style type="text/css">
.div1{
width: 100px;
height: 100px;
border: 1px solid #000000;
}
.div2{
width:40px ;
height: 40px;
background-color: green;
}
.div11{
position: relative;
}
.div22{
position: absolute;
top:50%;
left: 50%;
margin-top: -20px;
margin-left: -20px;
}
</style>
<div class="div1 div11">
<div class="div2 div22">
</div>
</div>
</body>
</html>方法三
利用css3的新增属性table-cell, vertical-align:middle;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>demo</title>
</head>
<body>
<style type="text/css">
.div1{
width: 100px;
height: 100px;
border: 1px solid #000000;
}
.div2{
width:40px ;
height: 40px;
background-color: green;
}
.div11{
display: table-cell;
vertical-align: middle;
}
.div22{
margin: auto;
}
</style>
<div class="div1 div11">
<div class="div2 div22">
</div>
</div>
</body>
</html>方法四
利用flexbox布局
直接在父元素上使用flexbox的布局
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>demo</title>
<style type="text/css">
.div1 {
width: 100px;
height: 100px;
border: 1px solid #000000;
}
.div2 {
height: 40px;
width: 40px;
background-color: green;
}
.div11 {
display: flex;
/*!*flex-direction: column;*!可写可不写*/
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div class="div1 div11">
<div class="div2 div22">
</div>
</div>
</body>
</html>
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论