Centering a Div Horizontally

by kirupa   |   29 January 2013

As much as we may like to think that all HTML elements are important and that they each play a unique role in making your documents work, you and I know that is not true. There are certain elements that are just funnier, smarter, nicer, and better looking than the rest. One such element is the very versatile div.

Div elements can be comfortably used across many situations, but one area they are especially comfortable in is layout. Their ability to act as a container without imposing themselves on their surroundings makes them especially popular for layout-related tasks...such as centering things on screen as shown in the following example:

centered window

In this short tutorial, I will explain how you can horizontally center div elements - those positioned normally as well as those positioned absolutely.

Let's get started!

Centering Div Elements

The most common way to horizontally center a div element is to set the margin-right and margin-left properties to auto:

#centerDiv {
    margin-left: auto;
    margin-right: auto;
}

You will often see this represented using the shorthand variation of margin as follows:

#centerDiv {
	margin: 0px auto;
}

This works across all sorts of div elements - ones with a fixed size, percentage size, positioned relative, and so on. The only time this doesn't work is if your div is absolutely positioned with its position property set to absolute. Don't worry, we'll look at that case next.

Centering an Absolutely Positioned Div Element

When a div is absolutely positioned, it pretty much defies the laws of physics. To horizontally center such an element, the margin approach you saw earlier is only partially there. You need to additionally specify the left and right properties with a value of 0px:

#centerDiv {
	margin: 0px auto;
	left: 0px;
	right: 0px;
}

Once you've added the entries for left and right, your absolutely positioned div element will also find itself horizontally centered.

Conclusion

There you have it! A really short tutorial that covers how to center div elements on the screen. If you inspect the CSS for this site (or many other sites that have large sections of content centered), chances are you will see a div that is centered using the exact techniques I've shown here.

If you have a question about this or any other topic, the easiest thing is to drop by our forums where a bunch of the friendliest people you'll ever run into will be happy to help you out!

THE KIRUPA NEWSLETTER

Get cool tips, tricks, selfies, and more...personally hand-delivered to your inbox!

( View past issues for an idea of what you've been missing out on all this time! )

WHAT DO YOU THINK?

NEWSLETTER

No spam. No fluff. Just awesome content sent straight to your inbox!

Awesome and high-performance web hosting!
BACK TO TOP
new books - yay!!!