Creating Responsive Images

To create a responsive image, use the max-width and height properties in CSS. This ensures that your images scale down to fit smaller screens, while maintaining their correct proportions.

Images on web pages should scale to fit all screen sizes. A "responsive" image is one that automatically resizes to fit its container, whether it's on a desktop or a smartphone.

The Basic CSS method

The most common way to make an image responsive is by adding the max-width and height CSS properties to your img tag or class:

How it works

Interactive Example

Below is a working example of a responsive image inside a resizable container:

View Output

In the preview window, try resizing the container (if supported by your browser) to see the image adapt to the new width.

Why Not Use width: 100%?

You might be tempted to use width: 100%, but max-width: 100% is generally better. With width: 100%, the image will stretch to fill the container even if the container is larger than the image's actual size (making it look blurry). With max-width: 100%, the image will only scale down to fit the container, but it will never grow larger than its original dimensions.

Advanced Responsive Images

While the CSS method above is perfect for most situations, HTML also provides more advanced ways to handle responsive images, such as the picture element and the srcset attribute. These allow you to deliver different image files based on the user's screen resolution or viewport size, which can further improve performance.

Read about the how to use the picture element for more advanced techniques.