1

I'm just starting out making simple webpages using HTML and CSS and I wanted to center my content in the middle of the page. With my code, I have the content centered from the left and the right, but I wanted to also center it from top and bottom. If you were to test my code, you would see that there is no spacing at the top. How would I fix this to have center from not only left and right but from top and bottom?

My CSS code looks something like this:

body {
width: 100%;
height: 100%;
background-color: green;
}

#homePage {
    width: 960px;
    height: 600px;
    background-color: white;
    margin: 0 auto;
}

My html code looks like this:

<body>
    <div id="homePage">
        <header> Logo and Twitter </header> 
        <ul id="pageNav">
            <li><a href="index.html">Home</a></li>
            <li><a href="features.html">Features</a></li>
            <li><a href="purchase.html">Purchase</a></li>
            <li><a href="contact.html">Contact</a></li> 
        </ul>               
        <footer> Content for footer goes here </footer>
    </div>                                  
</body>  

5 Answers5

2

Google "dead centre css". Mind the spelling. You'll get this invaluable link.

bishop
  • 37,830
  • 11
  • 104
  • 139
2

You could use positioning like this:

body {
    background-color: green;
}
#homePage {
    width: 960px;
    height: 600px;
    background-color: white;
    margin: auto;
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
}

jsFiddle example

By using absolute positioning on #homePage, setting the top, right, bottom, and left to zero, and the margin to auto, it will center horizontally and vertically.

j08691
  • 204,283
  • 31
  • 260
  • 272
1

Why don't you try to change the display? For example:

#homePage {
  width: 960px;
  height: 600px;
  background-color: white;
  margin: auto;
  display:block;
}
Pokechu22
  • 4,984
  • 9
  • 37
  • 62
0

The vertical middle align is not easy as horizontal align using width and margin. For me the best solution is

How to vertically center a div for all browsers?

it doesn't include any hack and fits with responsive design

Community
  • 1
  • 1
Raunak Kathuria
  • 3,185
  • 1
  • 18
  • 27
0

Great CSS trick by j08691! You can also try this on page load and re-size:

var _nBodyHeight = $('body').height();
var _nTop = (_nBodyHeight/2) - ($('#homePage').height()/2);
$('#homePage').css('top', _nTop);
Kunj
  • 1,980
  • 2
  • 22
  • 34