Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

How to Center an Image in CSS3

One of the most commonly asked questions about CSS3 is how to center an image on the page. Unfortunately, most of the answers you receive discuss just the <img> tag, without showing how to center a container. Using a container is important because you may want to add other items to that image later. The following procedure tells how to center the image.

  1. Open the SimpleGraphics.CSS file and add the following style.

    #ImageContainer img
    {
     height: 400px;
     width: 400px;
     margin: 0px;
    }

    The purpose of this style is to create an image of a specific size. There are a number of ways to deal with images of various sizes. This is one of them. It works well when most of your images are about the same size.

    In some cases, such as when you’re centering images of widely different sizes, you must resort to using JavaScript. In order to place an image in the center of the page, you must know the size of the image. Many third-party libraries make it easy for you to center images onscreen — the CSS-only technique does have limits.

  2. Add the following code to the #ImageContainer style.

    position: absolute;
    height: 400px;
    width: 400px;
    left: 50%;
    margin-left: -205px;

    This code sets the <div> position as absolute and gives it the same size as the image, so that the <div> and <img> tags are linked. It then places the left side of the <div> 50% across the page, so that no matter how the user changes the browser window, the left side of the <div> will remain center.

    Of course, you don’t want to center the left side of the <div> — you want to center the image. The margin-left setting moves the left margin 205 pixels to the left (half the overall size of the image, plus the padding), so that the center of the image is now in the center of the page.

  3. Save the CSS file and reload the page.

    You see the image and its frame centered on the page.

    image0.jpg
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.