本文转载自:简书
方法一
实现思路:使用两个div嵌套,外层div的宽高设置为浏览器视窗大小,相对定位。内层div绝对定位,将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>
<div class="outer-wrap">
<div class="login-panel">登录面板</div>
</div>
</body>
</html>
效果如下:
锤子科技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,效果特别好。
嗯!厉害了,没有用到JS,纯css。