Css – Vertically center rotated text with CSS

centeringcssvertical-alignmentvertical-text

I have the following HTML:

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

div.outer is a narrow vertical strip. div.inner is rotated 90 degrees. I would like the text "Centered?" to appear centered in its container div. I do not know the size of either div in advance.

This comes close: http://jsfiddle.net/CCMyf/2/. You can see from the jsfiddle that the text is vertically centered before the transform: rotate(-90deg) style is applied, but is somewhat offset after. This is particularly noticeable when div.outer is short.

Is it possible to center this text vertically without knowing any of the sizes in advance? I haven't found any values of transform-origin that solve this problem.

Best Answer

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/