先准備個測試模板
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .bg{ width:100%; height:100%; position: fixed; top:0; right:0; bottom:0; left:0; background-color: lightblue; } .text{ background:#fff; border-radius: 5px; } </style> </head> <body> <div class="bg"> <span class="text">單行文字水平垂直居中</span> </div> </body> </html>

內聯元素,沒有設置寬高
1、自身水平垂直居中
設置padding (左右方向有效,上下方向無效)

2、在容器內水平垂直居中
方法一:
position: absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);

方法二:flex布局(適合移動端)
display: flex;
justify-content: center;
align-items: center;
內聯塊元素,沒有設置寬高
1、自身水平垂直居中
設置padding
display:inline-block;
padding:30px 20px;

2、在容器內水平垂直居中
position: absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
塊元素,沒有設置寬高
1、自身水平垂直居中
display:block;
padding:20px 0;
text-align: center;

2、在容器內水平垂直居中
position: absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);

設置position為absolute,相當於把元素變為了inline-block,因此寬度沒有占據整行
如果需要的話,可以手動添加width
position: absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
width:100%;
指定容器寬高,內聯塊
display:inline-block;
width:200px;
height:100px;
1、自身水平垂直居中
單行文字可以使用line-height
text-align:center;
line-height:100px;
多行文字
display: flex;
justify-content: center;
align-items: center;
這種是將多行文字看做一個整體水平垂直居中,因此不是每一行文字都是水平居中效果

2、在容器內水平垂直居中
position: absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
或者
position: absolute;
top:50%;
left:50%;
margin-left:-100px;
margin-top:-50px;
指定容器寬高,塊元素
1、自身水平垂直居中
單行文字
display:block;
width:200px;
height:100px;
text-align:center;
line-height:100px;
多行文字
display: flex;
justify-content: center;
align-items: center;
2、在容器內水平垂直居中
position: absolute;
top:50%;
left:50%;
margin-left:-100px;
margin-top:-50px;
或者
position: absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
如果單純水平居中,可以控制margin
margin:0 auto;
