How To

How to Center an Image With CSS

Contributor
By Virginia DeBolt
eHow Contributing Writer
(1 Ratings)
How can you center this image?
How can you center this image?

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

Difficulty: Moderately Easy
Instructions

Things You'll Need:

  • An image to center
  • A web page or blog
  1. 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.

  2. 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.

  3. Step 3

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

  4. 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;
    }

  5. 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.

Post a Comment

Post a Comment
  • Have you done this? Click here to let us know.
I Did This

Related Ads

Internet
Virginia DeBolt,

Meet Virginia DeBolt eHow's Internet Expert.

Get Free Internet Newsletters

Copyright © 1999-2009 eHow, Inc. Use of this web site constitutes acceptance of the eHow Terms of Use and Privacy Policy.   en-US

Demand Media
eHow_eHow Technology and Electronics