How to Center an Image With CSS

By Virginia DeBolt

If you want to center an image on your web page, it's simple to do it with CSS. Here are the easy steps.

Things You'll Need

  • An image to center
  • A web page or blog

Step 1

If you want to center an image like that of the cowboys on horses shown above, first figure out what your CSS selector should be. The selector for an image is img. However, you may not want to use that selector alone, because if you do, every image on your page will be centered. Use a more specific selector to center just a single image or group of images.

Step 2

Here's a scenario: you want to center preview images in a sidebar. You have a div called #sidebar and a class called .preview for the images and links you are creating in sidebar. Your selector could be #sidebar .preview img. This selector selects any img element that is a descendant of any element with a class attribute that contains the word preview, which is a descendant of any element with an id attribute that equals sidebar. Your particular situation may be different, of course, but try to come up with a selector that is specifically aimed at only the images you want to center.

Step 3

Make the img a block level element. In the scenario above, this would be the CSS rule.#sidebar .preview img {display: block;}

Step 4

Add margin rules that will center the image. In the scenario above, this would be the complete rule.#sidebar .preview img {display: block;margin-right: auto;margin-left: auto;}

Step 5

The rule in Step 4 is all you need; just make sure your selector is specific enough to target only the images you want centered.