1.使用position定位+margin:auto
父级元素相对定位,子元素绝对定位,子元素四边都设置为0
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
margin: 0 auto;
height: 600px;
width: 600px;
background-color: #666;
position: relative;
}
.dv{
height: 200px;
width: 200px;
background-color: deepskyblue;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="box">
<div class="dv"></div>
</div>
</body>
</html>
2.使用position定位+margin-left/right/top/bottom
如果需定位的元素宽高已知,先设父元素为相对定位,子元素为绝对定位。把位置先定到宽高的50%,再用margin-top/left/bottom/right,值为自身一半的负数。
html:
<div class="box">
<div class="dv"></div>
</div>
css:
.box{
margin: 0 auto;
height: 600px;
width: 600px;
background-color: #666;
position: relative;
}
.dv{
position: absolute;
height: 200px;
width: 200px;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
background-color: deepskyblue;
}
3.用position定位+translate位移
这是在未知元素宽高时的用的居中方式,因为tranlate的值用百分比表示时,位移距离的是自身宽高的百分比的值。所以可以在1的基础上把marginmargin-top/left/bottom/right改成transform:translate(xxx%,xxx%)。
.dv{
position: absolute;
height: 200px;
width: 200px;
top: 50%;
left: 50%;
/* margin-top: -100px;
margin-left: -100px; */
transform: translate(-50%,-50%);
background-color: deepskyblue;
}
4.在弹性盒子中的居中
首先把盒子的display设置为flex,再设置垂直和水平居中,只需修改父级元素的属性值即可,
这是我个人比较喜欢的居中方式。
.box{
margin: 0 auto;
height: 600px;
width: 600px;
background-color: #666;
display: flex;
justify-content: center;
align-items: center;
}
.dv{
height: 200px;
width: 200px;
background-color: deepskyblue;
}
5.在网格布局中的居中
这与在弹性盒子的居中方式很类似,也是在父级元素上设置display:grid,再设置居中即可,也是只需修改父级元素属性值。
.box{
margin: 0 auto;
height: 600px;
width: 600px;
background-color: #666;
/* display: flex;
justify-content: center;
align-items: center; */
display: grid;
justify-items: center;
align-items: center;
}