The KIRUPA orange logo! A stylized orange made to look like a glass of orange juice!


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.


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.

Got a question or just want to chat? Comment below or drop by our forums (they are actually the same thing!) where a bunch of the friendliest people you'll ever run into will be happy to help you out!

When Kirupa isn’t busy writing about himself in 3rd person, he is practicing social distancing…even on his Twitter, Facebook, and LinkedIn profiles.

Hit Subscribe to get cool tips, tricks, selfies, and more personally hand-delivered to your inbox.


Serving you freshly baked content since 1998!
Killer hosting by (mt) mediatemple

Twitter Youtube Facebook Pinterest Instagram Github