Dare to Think | Web Design, Blog Development, Hosting and Print and Print made Simple
All made simple

Centre DIV Horizontally and Vertically using CSS

Here’s a quick guide on how to centre a DIV, both vertically and horizontally, in your web browser window. The main thing to remember is give your container div an absolute position and then the content div within a relative position.

Here’s what it looks like:

Center DIV in browser window

I always find it’s easier to download a page and play around with it in your own leisure so click here to download single html file containing HTML and CSS of the Centered DIV.

Here’s the code for those that don’t want to download:

CSS:

#container
{
position: absolute;
top: 50%;
left: 50%;
border: 3px solid black;
width: 400px;
height: 300px;
margin-left: -200px;
margin-top: -150px;
}

#content
{
font-size: 0.8em;
font-family: sans-serif;
background-color: #ccc;
position: relative;
left: 50%;
top: 50%;
width: 240px;
height: 50px;
margin-left: -120px;
margin-top: -25px;
}

HTML:

<div id=”container”>
<div id=”content”>
This content div is centered within it’s containing div
</div>
</div>

Related posts:

  1. DIV align bottom right (or left!)
  2. IE6 Div Height Problem
  3. Should you remove the border on clicked links
  4. Testing websites in IE6, IE7 and IE8 on a Mac
  5. Show and hide text in a form field using onclick and onblur
2 comments

2 Comments so far

  1. Jonno June 12th, 2009 8:17 pm

    Dude, your title is wrong (and redundant – when talking about web dev it’s assumed we’re talking about it being in a browser :-)

    Centering a div is just:

    #container {
    width:960px;
    margin:0 auto;
    }

    What you are describing is both horizontal AND vertical centering.

  2. alan June 12th, 2009 8:25 pm

    Thanks Jonno – I’ve changed the title accordingly.

Leave a reply