CSS: How to Center Your Images


If you have a paragraph(<p>) or a <div> with only images, it’s very easy to center them, just set the ‘text-align’ to ‘center':

p{ text-align: center }

What if there is other content in the paragraph, like text, and you don’t want it to be centered. Well, one way to do this, is to add a container, for example, a <div>, and the ‘text-align’ of the container to ‘center’. But this doesn’t look like a smart way, as the container is quite a waste. Can I do this within the <img>? Of course, you can make this happen with CSS, Check out the following code:

<img style=”display: block; clear: both; margin-left: auto; margin-right: auto;” src=”test.jpg” />

Just set the ‘display’ as ‘block’ and both the left and right margin as ‘auto’, that’s it, or you can add this to you CSS file:

p img{ display: block; clear: both; margin-left: auto; margin-right: auto; }

Let me know if you have a better idea.

This article is also posted on Gearor.com.

Leave a Reply