<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>demo</title> </head> <body > <style type="text/css"> body{ /* width: 100%; height:1000px; background: #67b374;*/ } .div1{ /* ,ie8及以下不支持 rgba */ position: absolute; height: 50px; width: 50px; margin: auto; top: 0; left: 0; bottom: 0; right: 0; background: #999; } .div2{ height: 50%; width: 50%; margin: auto; /*position: fixed;*/ position: absolute; background: aqua; top: 0; left: 0; bottom: 0; right: 0; } </style> <div class="div2"> <div class="div1"> </div> </div> <!--<div id="div4"> </div>--> </body> </html>
div1 ,div2 宽高都可以用百分比,优点是不用理会父元素大小,缺点 不支持 ie7及以下浏览器。
若 父元素 高度已知 ,可以通过 line-height 设置 垂直居中,再通过margin ,可以文本的 垂直水平居中