1.利用magin:auto方法
将盒子设置为margin,将其设置为绝对定位,给left,right,top,bottom值都设置为0
.box {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
width: 200px;
height: 200px;
margin: auto;
background-color: lightpink;
}
2.利用绝对定位的方法
先给盒子设置绝对定位,然后将left和top值都设置为50%,这时,盒子的左上角是刚好在网页的最中心的位置,然后再利用margin将其中心位置改到盒子最中心。
上代码
.box {
position: absolute;
left: 50%;
top: 50%;
margin: -100px 0 0 -100px;
width: 200px;
height: 200px;
background-color: lightpink;
}
3.利用transform属性
方法类似第二种,把其中margin改成了transform
.box {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
background-color: lightpink;
}
前面几种效果图如下
4.利用display:table-cell属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.parent {
width: 500px;
height: 500px;
display: table-cell;
vertical-align: middle;
text-align: center;
background-color: lightblue;
}
.child {
width: 100px;
height: 100px;
background-color: lightcoral;
display: inline-block;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">我是子元素</div>
</div>
</body>
</html>
5.利用display:flex布局实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.parent {
width: 500px;
height: 500px;
display: flex;
justify-content: center;
align-items: center;
background-color: lightblue;
}
.child {
width: 100px;
height: 100px;
background-color: lightcoral;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">我是子元素</div>
</div>
</body>
</html>
6
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.parent {
width: 500px;
height: 500px;
background-color: lightblue;
border: 1px solid #000;
}
.son {
width: 100px;
height: 100px;
margin-top: 200px;
margin-left: 200px;
background-color: lightpink;
border: 1px solid #000;
}
</style>
</head>
<body>
<div class="parent">
<div class="son"></div>
</div>
</body>
</html>