垂直居中:
1、最简单的就是知道父盒子和子盒子的高度,计算子盒子和父盒子的高度差,然后除以二,在子盒子中使用margin-top即可
2、display:table-cell和vertical-align:middle
display:table-cell属性让标签元素以表格单元格的形式呈现,类似于td标签

给父元素添加float和position(值为fixed和absolute)属性会破坏这个布局,给子元素添加position(值为fixed和absolute)属性也会破坏
3、给盒子添加绝对定位(子绝父相)
子盒子中设置top: 50%;transform: translateY(-50%);,这个情况可以不必知道子盒子的宽高也能垂直居中

水平居中
1、最简单的margin:0 auto;
2、将盒子转为行内快,然后使用text-align:center属性居中

3、使用绝对定位居中(子绝父相)

网友评论