1.利用弹性布局
display: flex;
align-items: center;
justify-content: center;
2.绝对定位(知道宽高)
position: absolute;
top: 50%;
left: 50%;
height: 400px;
400px;
margin-left: -200px;
margin-top: -200px;
3.绝对定位(知道宽高)
.box { 100px; height: 100px; position: absolute; left: 0; top: 0; right: 0; bottom: 0; margin: auto; } <div class="box"> 123123 </div>
4.绝对定位(不知道宽高)
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
需要注意的是:
绝对定位中设置了transform: translate(-50%,-50%);
假设宽高无法整除,会出现文字模糊问题
先检查元素宽高是否为奇数,如果是则改为偶数即可
5.table-cell
.box { position: relative; 100vw; height: 100vh; display: table-cell; vertical-align: middle; } .box-contant{ 200px; margin: 0 auto; } <div class="box"> <div class="box-contant">123123</div> </div>