引
元素的垂直水平居中在网页开发中极为常见,其实现方法也多种多样,接下来将介绍4种实现元素垂直水平居中的方法。实现效果如图:
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
一、 使用弹性盒模型flex实现
- 设置父元素的布局方式为flex, display: flex;
- 设置父元素在水平方向上的对齐方式为居中对齐,justify-content: center;
- 设置父元素在垂直方向上的对齐方式为居中对齐, align-items: center;
<style>
//标签默认会有内外边距,为了防止影响效果,一般先清除所有元素的默认边距
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
.father {
display: flex;
width: 400px;
height: 400px;
justify-content: center;
align-items: center;
background-color: skyblue;
margin: 200px auto;