在前端页面中经常会有垂直居中的排版布局,而在一些前端面试时,经常也会出关于让元素垂直居中,问你有几种方法来实现的问题。
下面就是我自己在实际开发中常用的几种css写法,大家可以参考,如果有比较新的方法,欢迎留言补充[笔芯]。
一、flex弹性布局
HTML代码
<div class="box">
<div class="contant"></div>
</div>
css代码
.box{
width: 100%;
height: 100vh;
display: flex; /* 启用flex弹性盒子 */
justify-content: center; /* 平行居中 */
align-items: center; /* 垂直居中 */
background-color: #f1f1f1;
}
.contant{
width: 200px;
height: 200px;
background-color: #dddddd;
}
渲染效果
二、绝对定位+css3属性
HTML代码
<div class="box">
<<