水平垂直居中 知道宽高
<div class="box">
<div class="child"></div>
</div>
.box {
width: 100vw;
height: 500px;
background: skyblue;
position: relative;
}
第一种:利用相对定位和绝对定位的margin:auto
.child {
width: 200px;
height: 200px;
background-color: deepskyblue;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
第二种:flxe 这种有没有宽高都可以用
.box {
width: 100vw;
height: 500px;
background: skyblue;
display: flex;
align-items: center;
justify-content: center;
}
.child {
width: 200px;
height: 200px;
background-color: deepskyblue;
}
第三:利用相对定位和绝对定位,再加上外边距和平移的配合 不知宽高也行
.box {
width: 100vw;
height: 500px;
background: skyblue;
position: relative;
}
.child {
width: 200px;
height: 200px;
background-color: deepskyblue;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
第四:利用textAlign和verticalAlign
.box {
width: 100vw;
height: 500px;
background: skyblue;
text-align: center;
}
.box:after {
content: "";
display: inline-block;
height: 100%;
width: 0;
vertical-align: middle;
}
.child {
display: inline-block;
vertical-align: middle;
}