CSS Tips: how to center an element


Often while developing a website, one can run into a variety of problems, causing a delay which will be spent looking for and testing possible solutions.

This is why I’ve decided to start the present article, dedicated exclusively to these “small big issues” that webdesigners run into on a daily basis. This week we will look at how to correctly center an element inside its container

Problem

You want to center an element in relation to its parent element.

Solution

Use the “auto” value for both margins (left and right), then define the length of this element

#centered {
	margin-left:auto;
	margin-right:auto;
	width:800px;
}

Explaining and looking at the “auto” value

CSS contain 7 unique properties set to define the horizontal format of an element: margin-left, border-left, padding-left, width, padding-right, border-right, margin-right. Their sum corresponds to the overall horizontal space that an element takes up on a given page.

Of the seven properties, three can accept regular values (percentages, pixels, points, em, ect.) as well as the “auto” value. These are the width of the element, the left-hand border and the right-hand one.

Having said this, there are four possible combinations that can be made:

  1. Two properties; one with an auto value, the other one with a fixed value.
  2. One property with an auto value, the other two with a fixed value.
  3. All three properties have a fixed value.
  4. All three properties have an auto value.

The first choice –two properties: one with an auto value, the other one with a fixed value – is the one that is of interest. When you set both margins to an auto value, while the width of the element is of fixed value, the browser will assign an equal length to both margins, thereby centering an element within its parent, as you can see for yourself in this example:

...
<body>
	<div id="centered">
		<p>Lorem ipsum....</p>
	</div>
</body>
</html>
#centered {
	margin-left:auto;
	margin-right:auto;
	width:800px;
}

Instead, when the auto value is applied to one margin and to the length of an element while the other margin is fixed, the auto margin becomes reduced to zero, thereby assigning the maximum possible width to the element, as you can see for yourself in this example:

#centered {
	margin-left:200px;
	margin-right:auto;
	width:auto;
}

In the second case, when one property has an auto value while the other one has a fixed one, the browser automatically sets the length of the latter property, as it is necessary to adhere to the preset values. For instance, if an element needs to be 960px in length and have a left-hand margin of 160px, the browser will automatically calculate the length that will be applied to the right-hand margin.

#box {
	margin-left:160px;
	margin-right:auto; /* margin calculated automatically to satisfy the other two values */
	width:960px;
}

This is the predefined setting that all browsers have. As a matter of fact, if you remove the line relative to the right-hand margin, it will appear in the same way, as you can see in the following example .

In the third case, when all three properties have a set value, the browser will force the right-hand margn to have an auto value, which brings us back to the previous case:

#box {
	margin-left:160px;
	margin-right:160px; /* forced to auto to the browser */
	width:960px;
}

In the fourth and last case, when you set both length and margins to auto, the browser will assign to the element a maximum length, in other words both right and left  margins will be reset to zero.

#box {
	margin-left:auto; /* forced to zero */
	margin-right:auto; /* forced to zero */
	width:auto;
}

Appendix: I’ve applied this method to an image but it doesn’t work, why not?

Automatic margins can be applied only to block elements: elements such as paragraphs, “div”, and lists which take up an entire line, thereby not allowing side elements to be added.

Images, “span”, “em”, “strong” are known as inline elements: elements that don’t create a block on their own, so they must be included in the block elements. Since they are considered parts of the text, “lateral” margins of the inline elements are ignored by web browsers. Therefore, in order to center images, we will have to set the “display” property to a “block” value, as it is illustrated in this example.

img { display:block; }

Master per Web Designer Freelance
In tutti questi anni abbiamo ricevuto centinaia di richieste di approfondimento sulle numerose tematiche del web design vissuto da freelance. Le abbiamo affrontate volta per volta. Ma ci siamo resi conto che era necessario fare qualcosa di più. Ecco perché è nato One Year Together, un vero e proprio master per web designer freelance che apre finalmente le porte al mondo del lavoro.
Scopri One Year Together »
[pdf]Scarica articolo in PDF[/pdf]
Tags: ,

The Author

Fond of web design, takes delight in creating (X)HTML+CSS layouts. A maniac of polished and tidy codes, the type of person you find in your house straightening the paintings hanging on the wall. He has made his mind of becoming a web designer with a capital “w”, and spends entire nights awake in order to make his dream come true.

Author's web site | Other articles written by

Related Posts

You may be interested in the following articles:

10 comments

  1. JOhny

Trackback e pingback

  1. uberVU - social comments
    Social comments and analytics for this post... This post was mentioned on Twitter by wdrss: CSS Tips: how to center an …
  2. Descubrimientos del 3 Marzo 2010 | Blog de unique3w
    [...] Truco CSS, cómo centrar un elemento. – CSS Tips: how to center an element | Your Inspiration Web [...]

Leave a Reply

Current month ye@r day *