Trying to center div horizontally and vertically in screen

user1141887 picture user1141887 · Jan 10, 2012 · Viewed 73.9k times · Source

I'm trying to make a div for my landing page of my website center in the very center of the screen, but it is not working.

Here is my code

CSS:

.centerDiv{
width:800px;
margin:0 auto;
border-radius: 5px;
background:#111;
padding:10px;}

HTML:

<div id="centerDiv" class="centerDiv">
   <h1>Title</h1>
   <p>Text will go here.</p>
</div>

Thanks.

Answer

Jassi picture Jassi · Jan 10, 2012

Note: If you're trying to center a div horizontally and vertically I would suggest looking into flexbox. You'll still need to provide fallback support, but flexbox is the future and it's amazing.

Update: flexbox is supported by all modern browsers now.

You need to give the div a static width and height first of all.

Second, you have to set position: absolute; and left: 50%; top: 50%; then you must do a margin-left and margin-top that are HALF of the height and width. It will then display correctly.

CSS:

.centerDiv{
  width: 800px;
  border-radius: 5px;
  background: #ccc;
  padding: 10px;
  height: 50px;
  position: absolute;
  margin-top: -25px;
  margin-left: -400px;
  top: 50%;
  left: 50%;
}

http://jsfiddle.net/wJ7dY/

P.S. I changed your styling a bit so you could actually read the text. Hope this helps!