CSS : centering absolute positioned text inside relative parent

vlad picture vlad · Aug 9, 2013 · Viewed 30.2k times · Source

How can I center absolute positioned text inside fluid relative parent? I'm trying to use text-align:center on parent elements but it always centers child's left corner, not element itself.

http://jsfiddle.net/sucTG/2/

Answer

amaurym picture amaurym · Aug 9, 2013

The thing is that position:absolute; modifies the element's width to fit its content, and that text-align: center; centers the text within the element block's width. So if you add a position: absolute; don't forget to increase the width of the element, or else the text-align: center; property will be useless.

The best way to solve this is to add a width: 100%; and a left: 0px; in the .text section.

http://jsfiddle.net/27van/