程度垂直居中分居中元素 定宽高 与不定宽高 两种状况。
不仅限本文的实现形式,本文只总结绝对罕用的形式。
如果有公共代码:
.wp {
border: 1px solid red;
width: 300px;
height: 300px;
}
.box {background: green;}
//size 仅定宽须要
.box.size{
width: 100px;
height: 100px;
}
<div class="wp">
<div class="box size">123123</div>
</div>
一、定宽高
absolute + 负 margin
absolute + margin auto
absolute + calc
1.absolute + 负 margin
.wp {
border: 1px solid red;
width: 300px;
height: 300px;
}
.box {background: green;}
.box.size{
width: 100px;
height: 100px;
}
2.absolute + margin auto
.wp {position: relative;}
.box {
position: absolute;;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
3.absolute + calc
.wp {position: relative;}
.box {
position: absolute;;
top: calc(50% - 50px);
left: calc(50% - 50px);
}
二、不定宽高
absolute + transform
lineheight
css-table
flex
grid
1.absolute + transform
.wp {position: relative;}
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
2.lineheight
.wp {
line-height: 300px;
text-align: center;
font-size: 0px;
}
.box {
font-size: 16px;
display: inline-block;
vertical-align: middle;
line-height: initial;
text-align: left; /* 修改文字 */
}
3.css-table
.wp {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.box {display: inline-block;}
4.flex
.wp {
display: flex;
justify-content: center;
align-items: center;
}
5.grid
.wp {display: grid;}
.box {
align-self: center;
justify-self: center;
}
总结:
PC 端有兼容性要求,宽高固定,举荐 absolute + 负 margin
PC 端有兼容要求,宽高不固定,举荐 css-table
PC 端无兼容性要求,举荐 flex
挪动端举荐应用 flex