CSS : centering absolute positioned text inside relative parent
Asked Answered
H

3

30

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/

Hazelwood answered 9/8, 2013 at 13:21 Comment(3)
Why do you need the position:absolute; in your .text class CSS ? I just tried removing that line and the text is correctly centered;Raffarty
because there will be relative elements in the blocks and I want text not to affect their positioning and just display on top of them.Hazelwood
To put something on top of the others, you just need positioning, not absolute necessarily.Crackdown
R
70

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/

Raffarty answered 9/8, 2013 at 13:39 Comment(1)
I'm no css guy, but the explanation was so fine, I really enjoyed the answer and it helped me fix my issue as well.Undergarment
G
16

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 **/
}
Gadson answered 19/6, 2019 at 5:25 Comment(0)
G
1

Update: What I put before was bad/wrong

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

This should be MUCH closer to what you want?

Your text is relative and your other 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%;
}
Garcon answered 9/8, 2013 at 13:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.