核心提示:方法一 实现思路:使用两个p嵌套,外层p的宽高设置为浏览器视窗大小,相对定位。内层p绝对定位,将top属性和left属性分别设置为50%,然后再设置负边距,大小分别是height和width的一半。 ...
方法一
实现思路:使用两个p嵌套,外层p的宽高设置为浏览器视窗大小,相对定位。内层p绝对定位,将top属性和left属性分别设置为50%,然后再设置负边距,大小分别是height和width的一半。
代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登录框居中问题</title> <style type="text/css"> *{margin: 0;padding: 0} html,body{height: 100%} /*这里很关键*/ .outer-wrap{ /*只有同时为html和body设置height: 100%时,这里的height才生效, 并且随浏览器窗口变化始终保持和浏览器视窗等高*/ height: 100%; position: relative; background-color: rgba(0, 0, 0, .5); } .login-panel{ width: 400px; height: 300px; background-color: orange; position: absolute; top: 50%; left: 50%; margin-top: -150px; margin-left: -200px; } </style> </head> <body> <p class="outer-wrap"> <p class="login-panel">登录面板</p> </p> </body> </html>
效果如下:

方法二
实现思路:给外层p设置相对定位,给内层p设置width,height,绝对定位,同时将top,left,bottom,right属性设置为0,margin为auto。
先看代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登录框居中问题</title> <style type="text/css"> *{margin: 0;padding: 0} html,body{height: 100%} /*这里很关键*/ .outer-wrap{ /*只有同时为html和body设置height: 100%时,这里才生效, 并且随浏览器窗口变化始终保持和浏览器视窗等高*/ height: 100%; position: relative; background-color: rgba(0, 0, 0, .5); } .login-panel{ width: 400px; height: 400px; background-color: orange; position: absolute; top: 0; left: 0; bottom: 0; right: 0; margin: auto; } </style> </head> <body> <p class="outer-wrap"> <p class="login-panel">第二种方法实现登录面板</p> </p> </body> </html>
效果如下:

我们常常使用定位的时候,一般情况下只设置上下、左右其中的一个,如果同时设置了top,bottom,left,right四个属性,只有top和left生效。所以这个方法妙就妙在设置了四个定位属性的同时设置了margin:auto。大家可以自己试一下。
这个方法用来设置内层p居中于外层p,效果特别好。