Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to center div horizontally and vertically in screen [duplicate]

Tags:

html

css

center

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.


2 Answers

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!

like image 119
Klikster Avatar answered Sep 09 '25 17:09

Klikster


This code (demo) allows for any width and height to be set, without having to update any other properties (e.g. top = height / 2) or relying on techniques that aren't well-supported (e.g. display:table;. The one downside is support for older IE versions is lacking. Combining this with another solution for IE only is probably you're best bet.

The CSS:

.absoluteCenter {
 /* Must manually set width/height */
 width:800px;
 height:500px;

 /* The magic centering code */
 margin:auto;
 position:absolute;
 top:0;bottom:0; /* Aligns Vertically - Remove for Horizontal Only */
 left:0;right:0; /* Aligns Horizontally - Remove for Vertical Only  */

 /* Prevent div from overflowing main window */
 max-width:100%;
 max-height:100%;
 overflow:auto;
}

/* IE 7 and Below */
:first-child+html .absoluteCenter,
* html .absoluteCenter {
 /* Place code here to override all above values, and add IE friendly centering */
}

And the HTML:

<div class="absoluteCenter">
 Content of DIV
</div>
like image 27
0b10011 Avatar answered Sep 09 '25 18:09

0b10011