个人总结出两种情况,即需要居中的元素带宽高、不带宽高,如下
带宽高
1
<style>
.father {
width: 500px;
height: 500px;
background-color: red;
position: relative;
}
.son {
width: 100px;
height: 100px;
background-color: blue;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
2
<style>
.father {
width: 500px;
height: 500px;
background-color: red;
position: relative;
}
.son {
width: 100px;
height: 100px;
background-color: blue;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
不带宽高
1
<style>
.father {
width: 500px;
height: 500px;
background-color: red;
position: relative;
}
.son {
background-color: blue;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
</style>
<body>
<div class="father">
<div class="son">son</div>
</div>
</body>
2
<style>
.father {
width: 500px;
height: 500px;
background-color: red;
display: flex;
justify-content: center;
align-items: center;
}
.son {
background-color: blue;
}
</style>
<body>
<div class="father">
<div class="son">son</div>
</div>
</body>