如何使用 CSS 居中旋转文本

How to Center Rotated text with CSS

我正在尝试编写一个带有旋转标签的栏。使用 transform:rotate 完成旋转。问题:width:100% 是在 之前 旋转计算的,因此它实际上将设置为旋转选项卡高度的 100%。

.tab-caption {
    position: absolute;
    width: 100%;  /* width before rotation! */
    top: 50%;
    height: 2px;  /* actual text will overlap! */
    margin-top: -1px;  /* subtract half the height */
    line-height: 0px;  /* centre the text on the base line */
    text-align: center;
    transform: rotate(90deg);
    white-space: nowrap;
}

即使文本与 div 重叠,垂直居中也能正常工作。对于水平居中,这个技巧不起作用;即使指定了 text-align:center,文本也总是从左边开始。

fiddle 在这里:http://jsfiddle.net/digorydoo/pzvuntd4/

在fiddle中,对于短字幕一切正常,因为旋转后变为宽度的高度比字幕短。对于长字幕,未正确居中。如何解决这个问题?

其实很简单:

.tab-caption {
    position: absolute;
    /* width: 100%; */ /* (remove this) width before rotation! */
    top: 50%;
    height: 2px;  /* actual text will overlap! */
    margin-top: -1px;  /* subtract half the height */
    line-height: 0px;  /* centre the text on the base line */
    text-align: center;
    left: 50%; /* added */
    transform: translateX(-50%) rotate(90deg); /* added translateX */
    white-space: nowrap;
}

演示 http://jsfiddle.net/pzvuntd4/2/