掌握多种CSS实现文字垂直居中的技术方案
Flexbox是现代CSS中最简单、最可靠的垂直居中方法。
<div style="display: flex; align-items: center; justify-content: center; height: 100px;"> 文字垂直居中 </div>
将元素显示为表格单元格,利用vertical-align属性实现居中。
<div style="display: table-cell; vertical-align: middle; text-align: center; height: 100px;"> 文字垂直居中 </div>
当容器高度固定时,将line-height设置为与height相同的值。
<div style="height: 100px; line-height: 100px; text-align: center;"> 文字垂直居中 </div>
适用于需要精确定位的场景。
<div style="position: relative; height: 100px;"> <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);"> 文字垂直居中 </div> </div>
对于现代浏览器,推荐使用Flexbox方法,代码简洁且功能强大。Table-cell方法兼容性好,Line-height方法简单直接但需要固定高度。根据具体需求选择合适的方法。