# 水平垂直居中
盒子的水平垂直居中是最常见的一个场景,这里介绍几种水平垂直居中方案:
<body>
<div>123</div>
</body>
/* 无效,因为没有设置父级高度 */
div{
height: 100%;
}
# 1. 定位
可以使用定位来实现水平垂直居中,将父盒子的 display
设为 relative
,将子盒子的 display
设为 absolute
,最后子盒子相对父盒子进行定位。
<div class="father">
<div class="son"></div>
</div>
html,
body{
height: 100%;
padding: 0;
margin: 0;
overflow: hidden;
}
.father{
height: 100%;
}
.son{
width: 100px;
height: 50px;
border: 1px solid #8c8c;
}
.father{
position: relative;
}
.son{
position: absolute;
top: 50%;
left: 50%;
//先左上角垂直水平居中
margin-top: -25px;
margin-left: -50px;
}
# 2. 定位(已知宽高)
在第一个方案的基础上做了修改。
.son{
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
# 3. 定位 + CSS3
优点:不需要知到子盒子道宽高。 缺点:有兼容性问题。
.son{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
# 4. flex 布局
优点:简单。 缺点:有兼容性问题
<div class="father">
<div class= "soon"></div>
</div>
.father{
display: flex;
justify-content: center;
align-items: center;
}
盒子的水平垂直居中是要注意以下几点:
注意
想要子元素宽度为100%,父盒子必须有高度。 我们在开发中很容易忽略的问题—— html. body 的宽高,它们只有默认宽度 100%,没有高度 ,是块级元素,而且 body 有个 8 px 的 margin。 这就意味着当我们给 body 元素的根元素设置 width: 100%; 时有效,设置 height: 100%; 会无效。