CSS垂直水平居中是一个经常需要面对的问题,也是一个面试常考的问题 0.0
text-align + line-height
12345
p{ text-align:center; height:20px; line-height:20px;}
margin + relative
12345678
//适用于已知宽高的div{ height:300px; margin:0 auto; //水平居中 position:relative; top:50%; margin-top:-150px;//垂直居中}
translate + relative
1234567
//适用于宽高未知的div{ margin:0 auto; position:relative; top:50%; transform:translateY(-50%);//使用CSS3的偏移属性实现垂直居中}
absolute
123456789101112131415161718
parent{ positive:relative;}//有两种实现方法child{ height:50px; width:80px; position:absolute; left:0;right:0; top:0;bottom:0; margin:auto;}child{ position:absolute; top:50%; left:50%; transform:translate(-50%,-50%)}
div{ display:flex; align-items:center; justify-contents:center;}
以上方法都可以自由组合,灵活运用,是情况使用