未知宽高的元素实现水平垂直居中html
方法一:父元素display:table; 子元素:display:cell-tableweb
优点,父元素能够动态改变高度布局
劣势:table属性容易形成屡次reflow,IE8如下不支持flex
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .parent1{ display:table; height:300px; width:300px; background-color:#FD0c70; } .parent1 .child{ display:table-cell; vertical-align:middle; text-align:center; color:#fff; font-size:16px; } </style> </head> <body> <div class="parent1"> <div class="child">hello world</div> </div> </body> </html>
方法二:利用空元素和伪类:code
优势:兼容性好orm
缺点:多出来个空元素,麻烦htm
如下代码的注释部分是替代after伪类的另外一种写法,原理同样it
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .parent{ position:absolute; width:100%; height:100%; text-align:center; background:#92b922; } .child{ background:#d93168; display:inline-block; color:#fff; padding:20px; } .parent:after{ display:inline-block; content:''; width:0px; height:100%; vertical-align:middle; } /* .vamb{ display:inline-block; width:0px; height:100%; vertical-align:middle; }*/ </style> </head> <body> <div class="parent"> <!-- <b class="vamb"></b> --> <div class="child">hello world</br>hello world</div> </div> </body> </html>
方法三,绝对定位+transformio
优势:方便,支持webkit内核table
缺点:transform兼容性差,IE9如下不支持
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .parent{ position:relative; width:300px; height:300px; background:#92b922; } .child{ position:absolute; top:50%; left:50%; color:#fff; background:red; transform:translate(-50%,-50%); } </style> </head> <body> <div class="parent"> <div class="child">hello world</br>hello world</div> </div> </body> </html>
方法四,flex布局
优势:方便
缺点:兼容性很差,IE支持不好
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .parent{ display:flex; justify-content:center; align-items:center; width:300px; height:300px; background:#92b922; } .child{ color:#fff; background:red; } </style> </head> <body> <div class="parent"> <div class="child">hello world</br>hello world</div> </div> </body> </html>