Constraining images with CSS

Small details make a big difference to websites. It’s never a good look when an image is larger than its container. Fortunately, it’s very easy to fix.

Responsive websites are great; mobile-first websites are even better. However, they do sometimes present frustrating issues. One issue which props up on a fairly regular basis is the issue of images – more specifically, a question along the lines of:

Why don’t my images fit on the page?

It’s a simple question really – if text can adapt to fit on a smaller screen, why do images sometimes insist on maintaining their original size? The answer is very simple.

Here’s a fairly average piece of code for an image:

<img src="image.png" alt="Image" width="800" height="200">

When displayed on a website, that image will display at a resolution of 800 pixels wide by 200 pixels high. If you’re using a screen with a lower resolution, the text will be scaled down and the image will dwarf the rest of the content. That’s because, without any other information, the browser doesn’t know any better.

So, to get around it, you need to add the following CSS:

img {
 max-width: 100%;
 height: auto;
 }

This does two things. First, it constrains all images to the maximum screen width. If that is 320 pixels, that’s the size the image will be scaled to. Second, it constrains the image height proportionally, so the image doesn’t look like it’s been squished.

So, what if you need to constrain not just images, but videos, and possibly more besides? Easy. Change your CSS to this:

.constrain {
max-width: 100%;
height: auto;
}

Now, you can use the .constrain class on any element and it will be constrained to the intended width.