Vertically center rotated text with CSS

前端 未结 7 1458
盖世英雄少女心
盖世英雄少女心 2020-12-07 11:56

I have the following HTML:

Centered?

div.

相关标签:
7条回答
  • 2020-12-07 12:32

    Removing : margin-top: -7px; from .inner made the vertically rotated text centered for me. It also made the horizontal text not centered.

    Just remove the above code?

    0 讨论(0)
  • 2020-12-07 12:33

    The key is to set position top and left to 50% and then transformX and transformY to -50%.

    .inner {
        position: absolute;
        top: 50%;
        left: 50%;
    }
    
    .rotate {  
        transform:  translateX(-50%) translateY(-50%) rotate(-90deg);
    }
    

    see: http://jsfiddle.net/CCMyf/79/

    0 讨论(0)
  • 2020-12-07 12:35

    The another option to rotate text 90 degree and center on axis Y is:

    .rotate-centered {
        top: 50%;
        right: 50%;
        position: absolute;
        transform: scale(-1) translate(-50%, 50%);
        writing-mode: vertical-lr;
     }
    
    <span class="rotate-centered">Text<span>
    

    Example: https://codepen.io/wwwebman/pen/KKwqErL

    But because of bad support in IE/EDGE writing-mode does NOT work there: https://developer.mozilla.org/en-US/docs/Web/CSS/writing-mode

    0 讨论(0)
  • 2020-12-07 12:37

    It may be a bit late for answering that question, but I stumbled on the same issue and found some way of achieving it, by adding another div in the way.

    <div class="outer">
        <div class='middle'><span class="inner rotate">Centered?</span></div>
    </div>
    

    and applying a text-align: center on that middle element, along with some positioning stuff:

    .middle {
        margin-left: -200px;
        width: 400px;
        text-align: center;
        position: relative;
        left: 7px;
        top: 50%;
        line-height: 37px;
    }
    

    The .inner also gets a display: inline-block; to enable both rotate and text-align properties.

    Here is the corresponding fiddle : http://jsfiddle.net/CCMyf/47/

    0 讨论(0)
  • 2020-12-07 12:52

    Can you add margin: 0 auto; to your "rotate" class to center the text.

    .rotate {
      -webkit-transform: rotate(-90deg);
      -ff-transform: rotate(-90deg);
      transform: rotate(-90deg);
      width: 16px;  /* transform: rotate() does not rotate the bounding box. */
      margin: 0 auto;
    }
    
    0 讨论(0)
  • 2020-12-07 12:52

    You could add this:

    $('.inner').css('margin-top', $(this).parent().height() - 2*$(this).height());
    

    To your .on('change') function, as you can see here: http://jsfiddle.net/darkajax/hVhbp/

    0 讨论(0)
提交回复
热议问题