Centering Elements with CSS

Problem

Mark writes:

I want the pictures of [some URI] to be in the middle. i already tried margin:auto but it didnt change anything.

thanks for your help

Thusly, we’ll be looking at centering an HTML element with CSS.

Solution

Simply and essentially, you set the width of the element, and give it left and right margins with the value of ‘auto’. Such should look something like:

.some_class {
 width: 600px;
 margin: 1.5em auto 3em auto;
}

Remember: this trick only works on block-level elements. A block-level element are those tags like <p>, <div>, <h1>, &c. Any element can be set as a block-level element by stating “display: block;” via CSS.

An example

Maria

Here’s the HTML for that silly image above:

<img src="http://www.alemmer.com/wp-content/uploads/2009/07/401558fe7b2c1ab9196e5baae8bfd1421.jpg" alt="Maria" id="maria" />

Now here’s the CSS:

1
2
3
4
5
6
#maria {
 margin: 0 auto;
 width: 150px;
 height: 150px;
 display: block;
}

The img tag is actually an inline-block-level element. As the element has to be block-level, we made the display: block; statement within #maria on line number five.

Let’s back-track a bit, though. What is this margin: 0 auto; nonsense? Basically, it’s what centers our image, and what is short for margin: 0 auto 0 auto;. The order direction is clockwise, as: top, right, bottom, & left.

  • Facebook
  • Twitter
  • Reddit
  • email
  • del.icio.us
  • Digg
  • MySpace
  • Slashdot
  • Google Bookmarks
  • Live
  • StumbleUpon
  • Technorati

One Response to “Centering Elements with CSS”

  1. mark says:

    cool thx

Leave a reply