Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center content in a absolute positioned div

I have an absolutly positioned element with content inside. It can be a <h1> or a few <p> tag. So I don't know the height of the content.

How can I vertically center the content inside the absolutly positioned div?

HTML :

<div id="absolute">
    <div class="centerd">
    <h1>helo</h1>
    <span>hi again</span>
    </div>
</div>   

CSS :

#absolute {
    position:absolute;
    top:10px;
    left:10px;
    width:50%;
    height:50%;
    background:yellow;
}

.centerd {
    display:table-cell;
    vertical-align:middle;
}

Fiddle

like image 369
user2324261 Avatar asked Apr 26 '13 14:04

user2324261


People also ask

How to align an absolute position within the center of a Div?

The element with the position: absolute CSS property is positioned relative to its nearest ancestor. We can also align the absolute positioned div element within the center by specifying the CSS property left along with the position: absolute property. The CSS left property will work only when we have already specified the position property.

How do I Center Center an absolutely positioned element in CSS?

Centering an absolutely positioned element is a CSS challenge that occurs now and then. The solution seems obvious once I’ve done it, but I still find myself googling the problem every few months. Horizontally centering a static element in CSS is normally handled by setting the left and right margins to auto, for example:

How to center the content within a <Div> Div?

In the end, we want to present a way of centering the content within a <div> both horizontally and vertically. Here, besides the justify-content and display (with "flex") properties, you need the align-items property which will set the vertical alignment to the center.

Can I use relative width on an absolutely positioned element?

However, this won’t work on an absolutely positioned element. Its location is determined in relation to the most immediate parent element that has a position value of absolute, relative, or fixed. In the following example, the relative red square has a width set to 40% of the available space.


3 Answers

Horizontal and vertical position absolute middle.

.center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50% , -50%);
  -webkit-transform: translate(-50%, -50%);
}
<div class="obj">
  <div class="center">Test</div>
</div>
like image 116
Celil Şahin Avatar answered Oct 04 '22 10:10

Celil Şahin


if you add display:table to your #absolute div you should get what you want:

http://jsfiddle.net/3KTUM/2/

like image 31
Pete Avatar answered Oct 04 '22 11:10

Pete


This can be done with flexbox too:

#absolute {
  align-items: center;
  display: flex;
  justify-content: center;
}
like image 11
Andrés Avatar answered Oct 04 '22 09:10

Andrés