Vertically center rotated text with CSS

danvk picture danvk · Feb 28, 2013 · Viewed 66.3k times · Source

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.

Answer

bjnsn picture bjnsn · Jun 19, 2014

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/