# Centering a Div Horizontally by [ kirupa](https://www.kirupa.com/me/index.htm) | 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](https://www.kirupa.com/snippets/examples/center_absolutely_positioned_div.htm): ![](https://www.kirupa.com/html5/images/center_window.png) 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.