下面是示例代码,现在想要让 box
元素居中于 .wrapper
元素:
<div class="wrapper">
<div class="box"></div>
</div>
绝对定位 + translate
.wrapper {
height: 100px;
position: relative;
}
.box {
width:50px;
height:50px;
/* 重点代码 */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
记得父元素要使用
position: relative;
定位。
绝对定位 + 负边距
.wrapper {
height: 100px;
position: relative;
}
.box {
width:50px;
height:50px;
/* 重点代码 */
position: absolute;
top: 50%;
left: 50%;
/* 这里要分别用元素自身宽高的一半 */
margin-top: -25px;
margin-left: -25px;
}
flex
直接改父元素:
.wrapper {
height: 20rem;
background-color:cadetblue;
/* 重点代码 */
display: flex;
justify-content: center;
align-items: center;
}
.box {
width:50px;
height:50px;
}
以上。