user2324261
user2324261

Reputation: 253

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

Upvotes: 25

Views: 40207

Answers (6)

Celil Şahin
Celil Şahin

Reputation: 261

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>

Upvotes: 22

Andr&#233;s
Andr&#233;s

Reputation: 256

This can be done with flexbox too:

#absolute {
  align-items: center;
  display: flex;
  justify-content: center;
}

Upvotes: 12

santhosh
santhosh

Reputation: 51

use text-align:center or left:50%

Upvotes: 1

Just make the div relative to its absolute parent and use text-align: center, like this:

.centerd {
    position: relative;
    width: 100%;
    text-align: center;
    /*display:table-cell;
    vertical-align:middle;*/
}

See example fiddle

Upvotes: 2

James Donnelly
James Donnelly

Reputation: 128791

Change your #absolute div to also use:

display:table;
vertical-align:middle;
text-align:center;

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

Upvotes: 7

Pete
Pete

Reputation: 58432

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

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

Upvotes: 14

Related Questions