CSS RWD Images


Images are commonly added in modern webpages. We can use the following methods to make them responsive.

Using the Width Property

If we set the width of an image element to a percentage and its height to auto, we can make the image to be responsive and scale with browser size.

Example 1:

Resize the browser window to see how the image below scales.

Rainbow cat.

Using the Max-Width Property

Sometimes our images scale up more than its original resolution. We will use the max-width property to fix this. This property will stop scaling the image up more than its original resolution.

Example 2:

Now resize this cat image again and see how it stops to its original size.

Rainbow cat.

Background Images

Background images can also respond to resizing and scaling. There are three different methods:

Example 3:

This first div element uses background image and set its background-size to "contain" which contains the image inside the div element while keeping its aspect ratio during resizing:

The second one is setting its background-size to "100% 100%" which makes the image to stretch out to 100% of the horizontal and vertical size of the div element even if its aspect ratio is compromised:

Last is using the background-size set to "cover" which covers all the div element like the previous one but this time the image keeps its original aspect ratio. This will also result to clipping to some parts of the image:

Different Images for Different Devices

We can use large images for bigger media devices like desktops and small images for smaller media devices. We can use media query to change the background image. If we want to change the image based on the device itself, we can use the property "min-device-width" which checks if the media device the user is using qualifies for the media query to fire and not the current viewport width.

Example 4:

The background-image of this div element will change from a big image to a small image if resized to below 992px.

The HTML Picture Element

The picture element specifies a group of images and uses the one that first satisfies a certain criteria such as the min/max width without using the media query in CSS. This is mostly used in responsive designs.

Example 5:

The images below uses the picture element and have different image sources inside and will be shown depending on the browser window size:

Random photos.