代码之家  ›  专栏  ›  技术社区  ›  digory doo

如何使用CSS居中旋转文本

  •  0
  • digory doo  · 技术社区  · 11 年前

    我想写一个带旋转标签的条形图。旋转是通过 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/

    在小提琴中,短字幕的一切都很好,因为旋转后变为宽度的高度比字幕短。对于长标题,居中操作不正确。如何解决此问题?

    1 回复  |  直到 11 年前
        1
  •  2
  •   Arbel    11 年前

    其实很简单:

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