(2019)[前端]面试题[6]:水平垂直居中方法
- 2019 年 11 月 13 日
- 筆記
问题
水平垂直居中的实现方式,尽可能多
Hello,欢迎来到我的博客,每天一道面试题,我们共同进步。
解答
这个有很多方法,我们一个个来说。
方法一:absoulte + transform(此方法未知子元素宽度)

<div class="parent"> <div class="child"> </div> </div>
.parent { background-color: #eee; width: 500px; height: 500px; margin: 10px auto; position: relative; } .child { width: 200px; height: 200px; background-color: lightcoral; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
说明:父元素相对定位,子元素绝对定位。 并且子元素top,left各50% 然后transform: translate(-50%, -50%); 此方法未知子元素宽高度(也就是说可以随便变换宽高度)
如果已知子元素宽高度,那么transform: translate(width/2,height/2);一样的效果。
(而这里就不能随便变换宽高度,变了就要改变translate的值)
方法二:flex布局
这是非常简单的一种方法

<div class="parent"> <div class="child"> </div> </div>
.parent { background-color: #eee; display: flex; justify-content: center; align-items: center; width: 500px; height: 500px; margin: 10px auto; } .child { width: 200px; height: 200px; background-color: lightgreen; }
将父元素设置为display: flex; justify-content: center; align-items: center; 都设置为居中对齐(分别为主轴居中,交叉轴居中) 涉及到flex语法,可以看flex相关文档/教程。
方法三:table-cell

<div class="parent"> <div class="child"> </div> </div>
.parent { background-color: #eee; display: table-cell; text-align: center; vertical-align: middle; width: 500px; height: 500px; margin: 10px auto; } .child { display: inline-block; width: 200px; height: 200px; background-color: lightslategray; }
简介: 父元素display:table-cell; 水平:text-align:center; 居中 垂直:vaertical-align: middle;居中 这还没完,需要子元素display:inline-block; ,不然只会垂直居中