001-如何让一个元素水平垂直居中
<div class="parent">
<div class="child"></div>
</div>
absolute + margin 方法
.parent {
position: relative;
width: 200px;
height: 200px;
border: 1px solid red;
.child {
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
margin-left: -50px;
margin-top: -50px;
background-color: violet;
}
}
absolute + transform 方法
.parent {
position: relative;
width: 200px;
height: 200px;
border: 1px solid red;
.child {
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
background-color: violet;
transform: translate(-50%, -50%);
}
}
flex 方法
.parent {
display: flex;
align-items: center;
justify-content: center;
width: 200px;
height: 200px;
border: 1px solid red;
.child {
width: 100px;
height: 100px;
background-color: violet;
}
}
grid 方法
.parent {
display: grid;
align-content: center;
justify-content: center;
width: 200px;
height: 200px;
border: 1px solid red;
.child {
width: 100px;
height: 100px;
background-color: violet;
}
}
部分答案整理自网络资源