You can CSS center images relatively simply. There are two techniques to center an image. one looks at the image as text, the other as a block.
See the image as text
One easy option is to CSS center an image by seeing it as text. We will use the following HTML:
<div class=”container”>
<img src=”https://www.hoasted.com/blog/wp-content/uploads/2015/04/Hoasted-puppy.jpg”>
</div>
So we have a div, inside which we have an image. To align the image in the center simply apply the following CSS:
text-align: center;
There is one important thing though, the CSS centering must be places on the element above the image. This does not work:
img {
text-align: center;
}
Instead, this works perfectly:
img {
text-align: center;
}
To see this code in action, check out this JSfiddle.
The reason the center attribute must be on the element above the image is that the text-align attribute specifies what to do with text inside a block. If you would have this for example, it would be impossible to CSS select the text itself:
<div> Hello </div>
Instead, you tell the <div> element to center it’s contents.
Seeing the image as a block
If you don’t want to see the image as text, you can view it as a block. You might want this because you don’t want to center everything inside an element, but just the image.
We start with the same HTML:
<div class=”container”>
<img src=”https://www.hoasted.com/blog/wp-content/uploads/2015/04/Hoasted-puppy.jpg”>
</div>
Instead of centering the everything inside the div, we apply the following CSS:
img {
width: 200px;
margin-left: auto;
margin-right: auto;
display: block;
}
If we translate this code to more human friendly:
- Make this image 200 pixels wide
- Automatically determine margin on the left and right
- View this image as a block
The margin: auto; command can be used to center things, but is dependent on 2 things:
- The object must have a defined width
- The object must be labeled as a block
You can see this code in action at this JSfiddle.
Some caveats
In my beginning CSS days I spend many hours trying to figure out the centering of objects. The most common thing to forget is to specify a width and to label an element as a block.
This gets double confusing because some elements are labeled as a block by default. So seemingly the margin: auto; sometimes works and sometimes doesn’t. This is not the case. If the auto command doesn’t work, your code is wrong 🙂