对容器设 display: flex + align-items: center + justify-content: center,就能可靠居中多行文本,兼容现代浏览器(chrome 29+、firefox 20+、safari 6.1+、edge 12+),无需计算行高或依赖行数,但容器必须有明确高度(如 height 或 min-height),且避免与 line-height 冲突。

用 display: flex 居中多行文本最稳
直接给结论:对容器设 display: flex + align-items: center + justify-content: center,就能可靠居中多行文本,兼容现代浏览器(Chrome 29+、Firefox 20+、Safari 6.1+、Edge 12+)。不用计算行高,不依赖文字行数,也不怕换行符或 <br> 干扰。
常见错误是只加 align-items: center 却忘了设 height 或 min-height——容器没高度,就“看不见”居中效果。另外,如果父容器用了 float 或 position: absolute,flex 可能失效,得检查层叠上下文。
- 容器必须有明确高度(比如
height: 200px或min-height: 100vh) - 子元素如果是
<p></p>或<div>,无需额外样式;如果是内联元素(如 <code><span></span>),建议加display: block避免意外换行错位 - 避免在 flex 容器上同时设
line-height,它会和align-items冲突,导致视觉偏移 -
<td style="vertical-align: middle">第一行<br>第二行</td>→ 有效 -
<td><div> <p>第一行</p><div class="aritcle_card flexRow artxards"> <div class="artcardd flexRow"> <a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill5117" title="HTML Extract"><img src="https://img.php.cn/upload/skill/000/000/081/179033952939354.jpg" alt="HTML Extract" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a> <div class="aritcle_card_info flexColumn"> <a rel="nofollow" href="/xiazai/skill5117" title="HTML Extract" class="overflowclass">HTML Extract</a> <p class="overflowclass">使用 MinerU 从 HTML 页面和文件中提取内容,将 HTML 转换为保持标题、列表、表格及文本层次结构的干净、结构化 Markdown。F...</p> </div> <a rel="nofollow" href="/xiazai/skill5117" title="HTML Extract" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a> </div> </div> <p>第二行</p> </div></td>→ 失效,需给<div> 加 <code>display: flex; align-items: center; - 不要给
<td> 设 <code>height同时又设padding过大,否则实际可用空间不足,文字会被截断line-height能不能用来居中单行?多行呢?line-height对单行文本有效——设成和容器高度相等即可居中;但多行时它会让每行都按该值撑开,结果是行间距爆炸,根本不是“整体居中”。比如容器高100px,文字两行,line-height: 100px会让两行分别距顶部和底部各50px,中间空一大截。- 仅适用于纯单行、无换行、字体大小固定的场景
- 响应式页面里字体随屏幕缩放,
line-height值很难匹配动态高度 - 如果用
rem或em设line-height,还得同步调整容器高度,维护成本高
IE11 兼容时的替代方案
IE11 支持 flex,但有个坑:
align-items: center在 flex-direction 为 column 时表现异常;更稳妥的是用绝对定位 + transform,或者表格布局。不过要注意,transform: translateY(-50%)必须配合top: 50%,且父容器得是position: relative。- 写法:
position: absolute; top: 50%; transform: translateY(-50%);,子元素需设position: relative(防止文字被裁) - 表格方案:
display: table-cell; vertical-align: middle;,但需给容器加display: table;和固定宽高 - 别用
margin-top算负值——行数一变就得重算,CSS 无法自动适应
真正麻烦的不是写法,而是当文本内容动态加载、高度不确定,又得兼容老浏览器时,flex 的
min-height和 JS 测高 fallback 往往得一起上。这时候别硬扛,先确认是否真需要支持 IE11。
表格单元格里多行文字怎么垂直居中
表格自带的 vertical-align: middle 只对单元格内容整体生效,但前提是内容不能是块级元素嵌套。如果 <td> 里直接放多行文本(含换行符或多个 <code><div>),<code>vertical-align 仍有效;但若套了 <div><p>…</p></div>,就得靠 flex 或重置 display。










