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/
First Method: We use 'left:0' , 'right:0' , and 'margin:auto' to achieve horizontal centering. Then, in order to achieve vertical centering, we use 'top: 50%' , which makes the element stay almost centered - this will only center the element according to its top boundary.
Answer: Use the CSS margin , left & right property You can align any absolutely or fixed positioned <div> element horizontally center using the CSS margin property in combination with the left and right position property.
The default value of position property is static . So the class . absolute has no parent that is relatively positioned. Therefore it stays relative to the viewport and appears all the time even when you scroll.
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 **/ }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With