要求让一个 div 垂直水平居中
方法一:flex 布局
div.parent {
display: flex;
justify-content: center;
align-items: center;
}
方法二:position 定位
1. div 宽高已知
div.parent {
position: relative;
}
div.child {
width: 50px;
height: 10px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -25px;
margin-top: -5px;
}
div.child {
width: 50px;
height: 10px;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
2. div 宽高未知
div.parent {
position: relative;
}
div.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
方法三:grid 布局
div.parent {
display: grid;
}
div.child {
justify-self: center;
align-self: center;
}
方法四:table 布局
div.parent {
display: table;
}
div.child {
display: table-cell
vertical-align: middle;
text-align: center;
}
方法五:inline-block
div.parent {
font-size: 0;
text-align: center;
&::before {
content: "";
display: inline-block;
width: 0;
height: 100%;
vertical-align: middle;
}
}
div.child {
display: inline-block;
vertical-align: middle;
}