Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS : centering absolute positioned text inside relative parent

Tags:

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/

like image 459
vlad Avatar asked Aug 09 '13 13:08

vlad


People also ask

How do you absolutely center an element within a parent?

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.

How do I center align an absolute div?

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.

Does position Absolute is kept relative to viewport?

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.


2 Answers

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/

like image 142
jeanpaul62 Avatar answered Dec 27 '22 18:12

jeanpaul62


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 **/ } 
like image 33
mCpXZKq3ruqgFXrvvAWRj9cYxk8RLX Avatar answered Dec 27 '22 19:12

mCpXZKq3ruqgFXrvvAWRj9cYxk8RLX