CSS: aligning images

Aligning images with CSS is one of the first techniques that you have to learn on your way to a proper CSS mastering. Basically, there's nothing difficult with this, provided that you have already a basic knowledge of floating and automatic margins. There are three basic alignments for images inside a block: left, right and center. The first two are easily achieved with floating, while the last one requires the use of left and right automatic margins. Let' start with the first two.

You want an image to be surrounded by text. Here's how you can do:

img.alignleft {
    float: left;
    margin: 0.3em 0.4em 0 0;

The image will be left-aligned and surrounded by text. But there's a catch: if text is not enough, our floating image will continue to affect other elements. To fix this problem, you can apply the following class to the image's container:

.img-clear {
   height: 100%;
   overflow: hidden;

By doing so, the image is self-contained within its parent element. Finally, you want an image to be horizontally centered within a block. Here's the code:

img.aligncenter {
 display: block;
 margin: 0 auto;

Our image has been turned into a block-level element in order to benefit from the particular rules of a block-formatting context, including the use of left and right automatic margins for centering an element along the x-axis. You can see all the examples below.


Live examples

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.