CSS常见的5种垂直水平居中(面试够用)

时间:2023-03-09 15:21:50
CSS常见的5种垂直水平居中(面试够用)

方法一 (flex)

<div id='box'>
<div class='child'></div>
</div>
#box{
width:200px;
height:200px;
background:blue;
display:flex;
align-items:center;
justify-content:center;
}
.child{
width:100px;
height:100px;
background:red;
}

方法二 (定位 传统布局 =>个人理解:四个方向设置+边距auto 让浏览器妥协渲染)

<div id='box2'>
<div class='child2'></div>
</div>
#box2{
width:200px;
height:200px;
background:blue;
position:relative;
}
.child2{
width:100px;
height:100px;
background:red;
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
}

方法三 (定位 css3)

<div id='box3'>
<div class='child3'></div>
</div>
#box3{
width:200px;
height:200px;
background:blue;
position:relative;
}
.child3{
width:100px;
height:100px;
background:red;
position:absolute;
top:50%;
left:50%;
transform: translate(-50%,-50%)
}

方法四 (定位 负边距 => 已知子元素宽高)

<div id='box4'>
<div class='child4'></div>
</div>
#box4{
width:200px;
height:200px;
background:blue;
position:relative;
}
.child4{
width:100px;
height:100px;
background:red;
position:absolute;
top:50%;
left:50%;
margin-top: -50px;
margin-left: -50px;
}

方法五 (转换为表格 table-cell)

<div id='box5'>
<div class='child5'></div>
</div>
#box5{
width:200px;
height:200px;
background:blue;
display:table-cell;
text-align:center;
vertical-align: middle;
}
.child5{
width:100px;
height:100px;
background:red;
display:inline-block;
}