不少状况下,网站的登陆框,就像这样css
这样html
这样前端
YouTube浏览器
或者这样微信
锤子科技学习
总之,登陆面板位于页面正中央,水平居中,竖直居中。而且 随着浏览器窗口大小变化,始终居中网站
实现思路:使用两个div嵌套,外层div的宽高设置为浏览器视窗大小,相对定位。内层div绝对定位,将top属性和left属性分别设置为50%,而后再设置负边距,大小分别是height和width的一半。
代码以下:url
<!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> <div class="outer-wrap"> <div class="login-panel">登陆面板</div> </div> </body> </html>
效果以下:spa
方法一code
锤子科技pc端的登陆页面就是用相似方法一的方式实现的
实现思路:给外层div设置相对定位,给内层div设置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> <div class="outer-wrap"> <div class="login-panel">第二种方法实现登陆面板</div> </div> </body> </html>
效果以下:
方法二
咱们经常使用定位的时候,通常状况下只设置上下、左右其中的一个,若是同时设置了top,bottom,left,right四个属性,只有top和left生效。因此这个方法妙就妙在设置了四个定位属性的同时设置了margin:auto。你们能够本身试一下。
这个方法用来设置内层div居中于外层div,效果特别好。
我的建了前端学习群,旨在一块儿学习前端。纯净、纯粹技术讨论,非前端人员勿扰!入群加我微信:iamaixiaoxiao。