1、transform方式
<div class="wp">
<div class="box size"></div>
</div>
<style>
.wp {
position: relative;
border: 1px solid red;
width: 300px;
height: 300px;
}
.box{
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border: 1px solid blue;
}
</style>
效果
2、margin + absolute
<div class="wp">
<div class="box size"></div>
</div>
.wp{
border: 1px solid red;
width: 300px;
height: 300px;
position: relative;
}
.box.size{
width: 100px;
height: 100px;
}
.box{
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
background: green;
}
效果
3、absolute + calc
<div class="wp">
<div class="box size"></div>
</div>
.wp {
position: relative;
border: 1px solid red;
width: 300px;
height: 300px;
}
.box {
position: absolute;;
top: calc(50% - 50px);
left: calc(50% - 50px);
width: 100px;
height: 100px;
background: green;
}
4、lineheight
<div class="wp">
<div class="box size">000</div>
</div>
.wp{
border: 1px solid red;
width: 300px;
height: 300px;
line-height: 300px;
text-align: center;
font-size: 0px;
}
.box{
font-size: 16px;
display: inline-block;
vertical-align: middle;
line-height: initial;
border: 1px solid blue;
}
效果
5、writing-mode
.wp {
writing-mode: vertical-lr; // writing-mode 属性定义了文本在水平或垂直方向上如何排布
text-align: center;
border: 1px solid red;
width: 300px;
height: 300px;
}
.wp-inner {
writing-mode: horizontal-tb;
display: inline-block;
text-align: center;
width: 100%;
}
.box {
display: inline-block;
margin: auto;
text-align: left;
}
- horizontal-tb:水平方向自上而下的书写方式。即 left-right-top-bottom
- vertical-rl:垂直方向自右而左的书写方式。即 top-bottom-right-left
- vertical-lr:垂直方向内内容从上到下,水平方向从左到右
- sideways-rl:内容垂直方向从上到下排列
- sideways-lr:内容垂直方向从下到上排列
6、css-table
<table>
<tbody>
<tr>
<td class="wp">
<div class="box">123123</div>
</td>
</tr>
</tbody>
</table>
.box {
display: inline-block;
background: green;
}
.wp {
text-align: center;
border: 1px solid red;
width: 300px;
height: 300px;
text-align: center;
}
7、flex
<div class="wp"> <div class="box">123123</div> </div>
.wp {
display: flex;
justify-content: center;
align-items: center;
}
8、grid
<div class="wp"> <div class="box">123123</div> </div>
.wp {
display: grid;
height: 200px;
border: 1px solid red;
}
.box {
align-self: center;
justify-self: center;
}