CSS垂直居中实现方式
CSS垂直居中是前端最最最常见的布局方式,能否写出一个兼容各浏览器的垂直居中CSS,也是初学者必备的技能之一,本文介绍几种常见的CSS垂直居中的实现方法,一定有一个是你喜欢的。一起动手实践起来吧!
CSS垂直居中实现方式
已知元素的组合,parent
, center
元素的基础样式如下
<style>
.parent {
width: 400px;
height: 400px;
border: 1px solid #333;
}
.center {
width: 40px;
height: 40px;
background-color: red;
}
</style>
<div className="parent">
<div className="center">
</div>
</div>
父元素flex + align-items(推荐)
只需要设置父元素
.parent {
display: flex;
align-items: center;
}
absolute + transform(推荐)
父元素相对定位,子元素绝对定位
.parent {
position: relative;
}
.center {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
grid + align-items(推荐)
只需要设置父元素
.parent {
display: grid;
align-items: center;
}
父级 table-cell 即可(推荐)
父元素设置 table-cell
和 vertical-align
.parent {
width: 400px;
height: 400px;
border: 1px solid #333;
display: table-cell;
vertical-align: middle;
}
absolute + margin: auto(推荐)
父元素相对定位,子元素绝对定位
.parent {
position: relative;
}
.center {
height: 50px;
position: absolute;
margin: auto;
top: 0;
bottom: 0;
}
absolute + 负margin(不推荐)
父元素相对定位,子元素绝对定位,前提需要知道子元素高度
.parent {
position: relative;
}
.center {
position: absolute;
top: 50%;
transform: translateY(-20px);
}
transform: translateY(-20px);
也可以改为 margin-top: -20px;
absolute + margin(不推荐)
知道父子元素的具体宽高
.center {
margin-top: 180px;
}