How to center images with CSS

I am aligned left! Meow.To center your image so that it always is in the middle using CSS means we have to make a small change to our CSS file and to our image tag.

The CSS

Telling an image to center means we need to create a center class in our CSS file...

img.center { 
    display: block;
    margin-left: auto;
    margin-right: auto;
}

The image tag

For the image we want centered we have to add the class "center"...

CSS code:
<img src="images/yourimagefile.jpg" class="center" />

That's it! You are done. (methods are described in detail below)



Techniques described

if you weren't sure what to do...

Here is a more detailed description of the above methods. We will explain everything.

Using CSS for centering

A CSS file contain instructions that your web pages use to display items in certain ways. In order to use CSS techniques, we must change both the CSS file and the HTML document.

First you must update your CSS file and add the following code...

img.center { 
    display: block;
    margin-left: auto;
    margin-right: auto;
}

In CSS this is called creating a "class". It is an instruction of how to display your image whenever that class is called. The name of this particular class is "center".

Once you have added this to your CSS file, you must tell the image what instructions to use. To do this, go to the image tag of the image you want to center and change it so that it knows what instructions to follow...

<img src="images/yourimagefile.jpg" class="center" />

In the above code you can see that we added a "class" and that it's name is "center". Now the image knows where to find instructions.

Once the CSS file and the HTML image tag is updated, the image will appear at the center of the page or area you placed it.
The picture will be centered even when you minimize or enlarge the browser window. In the CSS code we told it to "auto" margin both the left and right. This results in an equal area on both sides, therefore centering the image. Regardless of how large or small the area is that the image is located, the image will always stay center (or more exactly the image will always have equal margins to the left and right).