x
Architectural Blog, Modern Buildings & Casino Designs Loading...

Using max-width to resize images dynamically

When building a responsive website you will soon come across the problem of what to do with images that need to be able to resize dynamically based on the size of the viewport. Now if you are thinking that it’s all grey and hopeless you may be surprised to find that it is actually incredibly easy.

The method

The trick is to have the image in a container that is the size you want the image to be. The container can expand or contract and the picture will always try to be the full width using the max-width CSS property but it will never strectch further than it’s original dimensions. With a small IE8 fix this works all the way back to IE7.

<div class="image-wrapper">  <img src="/image.jpg" /></div>

You just then need to add a little bit of CSS:

.imagewrapper {  width: 100%; /* Or whatever width you want */}.imagewrapper img {  max-width: 100%;  height: auto;  width: auto; /* For IE8 */}

However, it is worth keeping in mind that the browser will have to load all of the images at their full size so it might pay to play around with the quality of your JPEGs until you get the right balance between file size and quality.

There is also an added bonus in that it makes your images look lovely and crisp on screens with hdpi display, iPhones for example, after shrinking the dimensions it will still use the full resolution!

Lovely.