多种CSS方法实现文本完美居中
使用现代CSS的Flexbox是最简单可靠的居中方式。
/* CSS */
.container {
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
height: 100px;
}
适用于需要脱离文档流的定位场景。
/* CSS */
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
使用display: table-cell实现垂直居中,配合text-align水平居中。
/* CSS */
.container {
display: table-cell;
text-align: center;
vertical-align: middle;
height: 100px;
width: 200px;
}
适用于单行文本,简单高效。
/* CSS */
.container {
height: 100px;
line-height: 100px; /* 与height相同 */
text-align: center;
}