CSS : centering absolute positioned text inside relative parent

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/


You can now achieve what you want more elegantly with flex. See for example:

HTML:

<div class="container">
  <div class="text">Your text</div>
</div>

CSS:

.container {
  position: relative; 
  width: 400px; /** optional **/
  height: 400px; /** optional **/
  background-color: red; /** optional **/
}

.text {
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center; /** Y-axis align **/
  justify-content: center; /** X-axis align **/
}