CSS: centering absolute positional text inside a relative parent

How can I center the absolute positional text inside the fluid relative to the parent? I am trying to use text-align:center for the parent elements, but it always centers the child left corner, not the element itself.

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

+11
html css centering css-position
source share
3 answers

The fact is that position:absolute; resizes the element to fit its content, and that text-align: center; centers the text within the width of the element block. Therefore, if you add position: absolute; , do not forget to increase the width of the element, otherwise the text-align: center; property text-align: center; will be useless.

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

http://jsfiddle.net/27van/

+26
source share

Update: what I put before was wrong / wrong

http://jsfiddle.net/brJky/1/

Should it be MUCH closer to what you want?

Your text is relative, and the rest of the elements inside the container are absolute!

 .text { color:#fff; padding:50px 0; display:block; position:relative; } .absolute { background:#f0f; height:25px; width:25px; position:absolute; top:36px; left:50%; } 
0
source share

Now you can 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 **/ } 
0
source share

All Articles