这是笔者近日面试中遇到的一个“辣手”问题,所谓辣手,是因为CSS这个货色不常常写的话,是肯定会忘,会手生的。笔者只是提及了最常见也是最简略的Flex,却被面试官持续诘问,本认为会依据记忆写进去点什么,最初却无奈。。。
话不多说了,上干货。
CSS垂直居中的形式,这里我都以父元素嵌套子元素的模式开展:
已知子元素的宽高的状况下:
absolute + margin:auto
.parent{ width:500px; height:500px; border:1px solid #ccc; position:relative;}.children{ width:300px; height:300px; background-color:red; position:absolute; top:0; right:0; bottom:0; left:0; margin:auto;}
absolute + -margin:
.parent{ /*同下面的盒子那样*/}.children{ width:300px; height:300px; background-color:red; position:absolute; top:50%; left:50%; margin-top:-100px; margin-left:-100px;}
子元素宽高未知的状况下:
flex布局:
.parent{ display:flex; justify-content:center; align-item:center;}
absolute + transform:
.parent{ position:relative; /*宽高同下面的盒子一样,这里不再反复设置了*/}.children{ position:absolute; top:50%; left:50%; transform:translate(-50%,-50%);}