We’ve covered aligning images to the left and right before, and today I want to talk about centering your images with CSS. If you remember the old way (without the magic of CSS), it was something like this:
<p align="center">centered image here</p>
Look familiar? There’s also:
<center>centered image here</center>
Of course, you don’t want to do that. Both ALIGN and CENTER here are deprecated- and besides, the beauty of CSS is that it’s supposed to make our lives easier, right? Now let’s say I want all of the images in my blog posts to be centered nicely. Instead of having to select each one and applying the dreaded ALIGN or CENTER, all I’d have to do, really, is this:
.post-body img { display: block; margin-left: auto; margin-right: auto }
I want to give you a quick explanation of what we’re doing here. The truth is that although I’ve been using that bit of code for a long time, I never thought to ask exactly how it worked. So here’s what this does:
First, it makes the image into a block – thereby making it unnecessary to add any additional <div> or <p> tags around it. Then it tells the browser displaying it to set left and right margins to auto.
When you set these to “auto”, what you are actually doing is telling the browser that you want left and right margins to be equal – which is really another way of describing centering.
Wasn’t that easy? How do you align your images?