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.
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!
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With