How to align a DIV vertically and horizontally

Oct 31, 2011

Table of contents:

  1. 1. Create your content DIV
  2. 2. Write the CSS

The other night I wanted to remake my person site I wanted to keep it simple with just my name and a small amount of text describing what I do. Aligning a DIV horizontally in HTML and CSS is really easy, but how do you align it vertically? Here’s how…

Note: The method I’m going to show you here only really works for content that is a fixed height. So if you’re looking for your DIV to expand, this isn’t the way you should do it. As always, I like to keep things as simple as possible. So here’s how I did it.

1. Create your content DIV

Nice and easy so far.

<div id="content">Hello World</div>

2. Write the CSS

Here’s the CSS you will need to align the DIV both vertically and horizontally.

#content {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 320px;
  margin-left: -160px;
  height: 480px;
  margin-top: -240px;

Some things to note. You need the negative margins to align the DIV and they should be exactly half of the width and height.

And that’s all you need. It’s a shame you can’t just use

margin: auto;

But then again there are a lot of things wrong with HTML and CSS.

Philip Brown


© Yellow Flag Ltd 2024.