<div class="wp">
<div class="box size">123123</div>
</div>
1. absolute + 负margin
.wp {
position: relative;
}
.box {
position: absolute;;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
2. absolute + margin auto
.box {
position: absolute;;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
3. absolute + calc
.box {
position: absolute;;
top: calc(50% - 50px);
left: calc(50% - 50px);
}
4. absolute + transform
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
5. 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; /* 修正文字 */
}
6. writing-mode
<div class="wp">
<div class="wp-inner">
<div class="box">123123</div>
</div>
</div>
.wp {
writing-mode: vertical-lr;
text-align: center;
}
.wp-inner {
writing-mode: horizontal-tb;
display: inline-block;
text-align: center;
width: 100%;
}
.box {
display: inline-block;
margin: auto;
text-align: left;
}
7. table
<table>
<tbody>
<tr>
<td class="wp">
<div class="box">123123</div>
</td>
</tr>
</tbody>
</table>
.wp {
text-align: center;
}
.box {
display: inline-block;
}
8. css-table
.wp {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.box {
display: inline-block;
}
9. flex
.wp {
display: flex;
justify-content: center;
align-items: center;
}
10. grid
.wp {
display: grid;
}
.box {
align-self: center;
justify-self: center;
}
作者:颜海镜
链接:https://juejin.im/post/5b9a4477f265da0ad82bf921
来源:掘金
网友评论