.div1{
width: 200px;
height: 200px;
background-color: blue;
}
.div2{
width: 100px;
height: 100px;
background-color: red;
}
<div class="div1">
<div class="div2"></div>
</div>
如何实现子元素(红色部分)水平+垂直居中的效果呢?
1、flex布局
.div1{
width: 200px;
height: 200px;
background-color: blue;
display: flex;
justify-content: center;
align-items: center;
}
2、定位+marge:auto
.div1{
width: 200px;
height: 200px;
background-color: blue;
position: relative;
}
.div2{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
3、定位(已知元素的宽高)
设置与顶部和左边的距离:top: 50%; left: 50%; 设置左外边距与上外边距的距离: margin-left: -50px; margin-top: -50px;减去元素自身高度宽度的一般即可
.div1 {
width: 200px;
height: 200px;
background-color: blue;
position: relative;
}
.div2 {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
4、定位+calc(已知元素的宽高)
.div1 {
width: 200px;
height: 200px;
background-color: blue;
position: relative;
}
.div2 {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 50px);
}
5、定位+translate(元素宽高未知)
.div1 {
width: 200px;
height: 200px;
background-color: blue;
position: relative;
}
.div2 {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 50% ;
left: 50%;
transform: translate(-50%,-50%);
}