标签:flex img block ack set class char 宽高 ica
1.利用绝对定位
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>水平垂直居中</title> <style> .center{ position:absolute; top:50%; left:50%; width:100px; height:30px; margin-top: -15px; margin-left: -50px; border:1px solid red; text-align:center; background: red; } </style> </head> <body> <div class="center">垂直水平居中</div> </body> </html>
top与left设为50%,margin-left为宽度一半的负值,margin-top为高度一半的负值
此方法最常见,但仅仅适用于已知宽高的情况下。
2.绝对定位结合transform
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>水平垂直居中</title> <style> .center{ position:absolute; top:50%; left:50%; width:100px; height:30px; -webkit-transform: translate(-50%, -50%); -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); border:1px solid red; text-align:center; background: red; } </style> </head> <body> <div class="center">垂直水平居中</div> </body> </html>
可在未知宽高时使用,但在IE8及以前的浏览器内不支持,且内部文本可能因为移动而稍显模糊
3.利用flex
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>水平垂直居中</title> <style> .cont-center { height: 500px; -webkit-display: flex; -moz-display: flex; display: flex; justify-content: center; align-items: center; } .center{ width:100px; height:30px; background: red; } </style> </head> <body> <div class="cont-center"> <div class="center">垂直水平居中</div> </div> </body> </html>
IE11以下不支持justify-content、align-items等属性
4.利用ifc布局,即空的img或者伪元素
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>水平垂直居中</title> <style> .cont-center { height: 500px; text-align: center; font-size: 0; -webkit-text-size-adjust: none; } .center{ width:100px; height:30px; font-size: 15px; background: red; vertical-align: middle; display: inline-block; } .cont-center:after { content: ‘‘; width: 0; height: 100%; display: inline-block; vertical-align: middle; } </style> </head> <body> <div class="cont-center"> <div class="center">垂直水平居中</div> </div> </body> </html>
5.利用calc
根据雅虎的35个前端优化法则,并不提倡使用calc,略过。
标签:flex img block ack set class char 宽高 ica
原文地址:http://www.cnblogs.com/yanze/p/7625668.html