1:使用绝对定位使盒子在页面居中
将盒子设置为绝对定位,将top,bottom,left,right值设置为0,margin:auto;
<head>
<title>居中</title>
<style type="text/css" >
.div1{
width: 500px;
height: 300px;
background: #00f;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="div1">
</div>
</body>
2:使用绝对定位使盒子在页面中居中
①:给要居中的盒子做绝对定位
②:将left值设为calc(50% - 盒子宽度的一半),top值设为calc(50% - 盒子高度的一半)
<head>
<title>居中</title>
<style type="text/css">
.div1{
width: 500px;
height: 300px;
background: #00f;
position: absolute;
left: calc(50% - 250px);
top: calc(50% - 150px);
}
</style>
</head>
<body>
<div class="div1"></div>
</body>