
本文介绍使用 writing-mode 和 text-orientation 替代 CSS transform: rotate(),解决 Bootstrap 4 表格中旋转文字溢出单元格、无法垂直居底+水平居中的问题,并提供兼容性良好、语义清晰的纯 CSS 方案。
本文介绍使用 `writing-mode` 和 `text-orientation` 替代 css `transform: rotate()`,解决 bootstrap 4 表格中旋转文字溢出单元格、无法垂直居底+水平居中的问题,并提供兼容性良好、语义清晰的纯 css 方案。
在 Bootstrap 4 中实现表头文字垂直旋转(如 -90°),同时确保文字严格居中于单元格内、底部对齐、不溢出边框,是常见但易踩坑的布局需求。传统方案依赖 transform: rotate(-90deg) 配合 transform-origin,但其本质是“视觉位移”,会脱离文档流,导致计算高度失准、文字悬出单元格、响应式错位等问题——这正是原问题中“rotated text outside cell borders”的根本原因。
更现代、更稳健的解法是采用 CSS 写入模式(Writing Mode):
.table-rotated-header {
writing-mode: vertical-rl; /* 文字从上到下排列(右→左书写方向) */
text-orientation: mixed; /* 关键:使字母保持水平朝向,避免倒置 */
white-space: nowrap;
text-align: center; /* 水平居中(针对垂直排布下的“行内”对齐) */
padding: 12px 8px; /* 可选:微调内边距提升视觉平衡 */
}
✅ 优势说明:
- vertical-rl 将文本自然转为垂直流,浏览器按真实尺寸渲染单元格高度;
- text-orientation: mixed 确保英文字母不被侧躺,而是保持正立(即“竖排横写”效果),符合中文/英文混合场景习惯;
- 完全脱离 transform,无重绘偏移,自动适配 th 的盒模型,支持 text-align 和 padding 精确控制;
- 原生支持 Bootstrap 4 的 .table 类及响应式类(如 .text-center),无需额外 hack。
完整可运行示例(精简版)
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Bootstrap 4 垂直表头教程</title><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css"><style>
.table-rotated-header {
writing-mode: vertical-rl;
text-orientation: mixed;
white-space: nowrap;
text-align: center;
padding: 16px 6px; /* 上下留白增强可读性 */
font-weight: 500;
}
/* 优化表头高度一致性(可选) */
thead th {
vertical-align: bottom;
}
</style>
配置选项 |
|||
|---|---|---|---|
国家 |
白色漆面 | 红色漆面 | 黑色内饰 |
| 德国 | ✓ | ✓ | ✓ |
| 日本 | ✓ | — | ✓ |
注意事项与兼容性
- 浏览器支持:writing-mode 和 text-orientation 在 Chrome 48+、Firefox 41+、Edge 12+、Safari 14.1+ 中稳定支持;IE11 仅部分支持(建议降级为常规水平表头或使用 Modernizr 检测后 fallback);
- 不要混用 transform:一旦启用 writing-mode,再叠加 transform: rotate() 会导致行为不可预测,应彻底弃用;
- 高度自适应:垂直文本高度 ≈ 字体大小 × 字符数 + 行高,若需固定高度,推荐设置 min-height 而非 height,避免截断;
- 移动端适配:小屏幕下垂直表头可读性下降,建议配合媒体查询,在 @media (max-width: 767.98px) { .table-rotated-header { writing-mode: horizontal-tb; text-orientation: upright; transform: none; } }
综上,放弃“旋转盒子”的旧思路,拥抱 writing-mode 的语义化垂直流,是 Bootstrap 4 中实现专业级垂直表头的首选方案——它更轻量、更稳定、更易维护,且天然契合现代 CSS 布局哲学。










