在W3CPlus學習CSS垂直居中第六種方案時,發現兩個棘手問題:引入無語義標籤、文本換行失效。經過測試驗證,找到了完美解決方案,分享給踩坑的同學。
原方案需添加無語義`
使用`:before`偽元素創建基準線,消除額外DOM節點:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>水平垂直居中</title>
<style>
.wrapper {
width: 200px;
height: 200px;
background: skyblue;
}
.wrapper:before {
content: '.';
display: inline-block;
vertical-align: middle;
height: 100%;
}
.content {
display: inline-block;
text-align: center;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="content">多行文字居中 多行文字居中 多行文字居中</div>
</div>
</body>
</html>

但inline-block特性產生字符間隙,導致文本換行偏移。
父容器`font-size: 0`消除間隙,子元素重置`font-size: 16px`恢復字號:
.wrapper {
font-size: 0;
}
.content {
font-size: 16px;
}

完美解決!多行文字水平垂直居中,無多餘標籤,無換行偏移,代碼極簡優雅。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>水平垂直居中完美版</title>
<style>
.wrapper {
width: 200px;
height: 200px;
background: skyblue;
font-size: 0; /* 關鍵:消除inline-block間隙 */
}
.wrapper:before {
content: '.';
display: inline-block;
vertical-align: middle;
height: 100%;
}
.content {
display: inline-block;
text-align: center;
font-size: 16px; /* 關鍵:恢復文本字號 */
}
</style>
</head>
<body>
<div class="wrapper">
<div class="content">多行文字居中
多行文字居中
多行文字居中</div>
</div>
</body>
</html>
這個方案兼容性好、語義純粹、無副作用,是目前多行文字水平垂直居中的最優解之一。收藏備用,下次不再踩坑!