【问题标题】:How to Center Rotated text with CSS如何使用 CSS 将旋转文本居中
【发布时间】:2015-04-08 21:44:19
【问题描述】:

我正在尝试编写一个带有旋转标签的栏。使用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,文本也总是从左边开始。

小提琴在这里:http://jsfiddle.net/digorydoo/pzvuntd4/

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

【问题讨论】:

    标签: css rotation transform centering


    【解决方案1】:

    其实很简单:

    .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/

    【讨论】:

    • 太棒了!我不知道 translateX 可以使用百分比!谢谢!
    猜你喜欢
    • 2013-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 2019-12-31
    • 2018-04-26
    • 1970-01-01
    相关资源
    最近更新 更多