这是面试常问的题目。今天就来彻底搞明白水平垂直居中的方法
一共七种方法,前两种是定宽高才能用的,后面五种不管需要垂直居中的元素有没有宽高都可以垂直居中。flex和table-cell和grid都需要有父元素的宽高,也就是说不能直接在body中水平垂直居中。
<body>
<div class="container">
<div class="box">我是小盒子</div>
</div>
</body>
1.定宽高 绝对定位 + left/right/bottom/top + margin
.box{
height: 200px;
width: 200px;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
background-color: red;
}
2.定宽高 绝对定位和负magin值
.box{
height: 200px;
width: 200px;
background-color: red;
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
}
3.有宽高和无宽高是一样的 绝对定位 + transform
.box{
height: 200px;
width: 200px;
background-color: red;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
4.有宽高和无宽高是一样的 flex 父元素必须要有宽高
.container{
height: 500px;
width: 500px;
background-color: yellow;
display: flex;
justify-content: center;
align-items: center;
}
.box{
height: 200px;
width: 200px;
background-color: red;
}
5.有宽高和无宽高是一样的 grid 父元素必须要有宽高
.container{
height: 500px;
width: 500px;
background-color: yellow;
display: grid;
}
.box{
/* height: 200px;
width: 200px; */
background-color: red;
margin: auto;
}
6.有宽高和无宽高差不多 父元素必须要有宽高 table-cell + vertical-align + 直接设置成这个inline-block有宽高无宽高一样。设置margin: auto则时有宽高
.container{
height: 500px;
width: 500px;
background-color: yellow;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.box{
height: 200px;
width: 200px;
background-color: red;
//margin: auto;
display: inline-block;
}
7.定宽高不定宽高可以 flex变异
.container{
height: 500px;
width: 500px;
background-color: yellow;
display: flex;
}
.box{
//height: 200px;
//width: 200px;
background-color: red;
margin: auto;
}