CSS: scaling and resizing images

I devoted some of my previous posts to this subject, but I think that the whole idea of scaling and resizing images with CSS should be revised in the light of some new considerations. First of all, if you want to achieve a flexible result, never use pixels. Instead, turn your images into block level elements and use percentages on image dimensions. Pixels are good when you work with fixed-width layouts, but always remember that a browser is not Photoshop because in CSS it doesn't exist a property to keep the image ratio intact. In other words, you can't write something like this:

#gallery ul li img {

    preserve-ratio: true;
    width: 200px;
    height: 150px;
    display: block;


For example, consider the following image sample, which is a 460 x 288 JPEG picture:

Now we want to build an image gallery using the above image as a prototype. We can write something like this:

#gallery {
 width: 400px;
 margin: 0 auto;
 padding: 0;
 list-style: none;
 overflow: hidden;

#gallery li {
 width: 180px;
 margin-right: 5px;
 margin-bottom: 5px;
 padding: 5px;
 background: teal;
 border-radius: 6px;
 border: 1px solid black;
 float: left;

#gallery li img {
 display: block;
 width: 100%;

We're using dimensions expressed in percentages here for all the images contained within our gallery. I've chosen to use pixels for the parent containers just to create a correlation with the original image dimensions, but this example works even if I had specified dimensions in percentages on the parent elements. And here is the result:

As you can see, images scale well along with their containers. But remember: this technique works only when the intrinsic dimensions of the image are greater than or equal to the dimensions of its container. In our case, if the li elements were, say, 500 pixels wide, then all the images would be displayed distorted by browsers.

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.