原文链接:CSS实现水平垂直居中的1010种方式 (https://cloud.tencent.com/developer/article/2035014)
一、目录
1.1 居中元素固定宽高使用
1.2 居中元素无固定宽高
二、居中元素固定宽高使用
2.1 absolute + 负值margin
<!-- HTML -->
<div class="father">
<div class="son"></div>
</div>
/* CSS */
.father {
position: relative;
width: 200px;
height: 100px;
border: 1px solid red;
}
.son {
width: 100px;
height: 50px;
background-color: rgb(102, 179, 102);
/* 核心代码 */
position: absolute;
left: 50%;
top: 50%;
margin-top: -25px;
margin-left: -50px;
}
2.2 absolute + margin:auto
<!-- HTML -->
<div class="father">
<div class="son"></div>
</div>
/* CSS */
.father {
position: relative;
width: 200px;
height: 100px;
border: 1px solid red;
}
.son {
width: 100px;
height: 50px;
background-color: rgb(102, 179, 102);
/* 核心代码 */
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
2.3 absolute + calc
<!-- HTML -->
<div class="father">
<div class="son"></div>
</div>
/* CSS */
.father {
position: relative;
width: 200px;
height: 100px;
border: 1px solid red;
}
.son {
width: 100px;
height: 50px;
background-color: rgb(102, 179, 102);
/* 核心代码 */
position: absolute;
left: calc(50% - 50px);
top: calc(50% - 25px);
}
三、居中元素无固定宽高
3.1 absolute + transform
<!-- HTML -->
<div class="father">
<div class="son"></div>
</div>
/* CSS */
.father {
position: relative;
width: 200px;
height: 100px;
border: 1px solid red;
}
.son {
width: 100px;
height: 50px;
background-color: rgb(102, 179, 102);
/* 核心代码 */
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
3.2 lineHeight
<!-- HTML -->
<div class="father">
<div class="son">lineHeight</div>
</div>
/* CSS */
.father {
position: relative;
width: 200px;
height: 100px;
border: 1px solid red;
/* 核心代码 */
line-height: 100px;
text-align: center;
font-size: 0px;
}
.son {
background-color: rgb(102, 179, 102);
/* 核心代码 */
font-size: 16px;
display: inline-block;
vertical-align: middle;
line-height: initial;
text-align: left;
}
3.3 table
<!-- HTML -->
<table>
<tbody>
<tr>
<td class="father">
<div class="son">table 水平垂直居中</div>
</td>
</tr>
</tbody>
</table>
/* CSS */
.father {
position: relative;
width: 200px;
height: 100px;
border: 1px solid red;
/* 核心代码 */
text-align: center;
}
.son {
background-color: rgb(102, 179, 102);
/* 核心代码 */
display: inline-block;
}
3.4 flex
<!-- HTML -->
<div class="father">
<div class="son"></div>
</div>
/* CSS */
.father {
position: relative;
width: 200px;
height: 100px;
border: 1px solid red;
/* 核心代码 */
display: flex;
justify-content: center;
align-items: center;
}
.son {
width: 100px;
height: 50px;
background-color: rgb(102, 179, 102);
}
3.5 grid
<!-- HTML -->
<div class="father">
<div class="son"></div>
</div>
/* CSS */
.father {
position: relative;
width: 200px;
height: 100px;
border: 1px solid red;
/* 核心代码 */
display: grid;
}
.son {
width: 100px;
height: 50px;
background-color: rgb(102, 179, 102);
/* 核心代码 */
align-self: center;
justify-self: center;
}