In this CSS tutorial, we will learn some tricks on how to make Images responsive.
Width Property
In responsive web designing we always use the relative percentage value for the width and other length related properties, so does for images. We can set the width property to any percentage value and set the height property to auto. This will make the image responsive to the scaling up and down of the browser window.
Example
using the max-width Property
If we set the
width
of the image to
100%
then the image will scale up than its original size if the browser window display size increases. So for many cases, it would be a good idea to set the
max-width
property to
100%
instead of
width.
By setting the
max-width
we specify that the image will not scale up from its original size, but it can scale down. This maintains the aspect ratio (width by height ratio) of the image.
Example
Background Images
Like the normal images, the
background-image
of the element also resizes and scales according to the browser display area. Let’s discuss the three methods of background-size property for the background images.
background-size:contain;
If the
background-size
is set to
contain
value, the image will try its full to fit in the element box, but here the image will prioritize its aspect ratio. The image will not cover the element box completely if the aspect ratio is distorting.
Example
background-size:100% 100%
By specifying the
background-size
to
100% 100%
; we actually specifying the background image width and height to the element 100% width and height. In this, the image will cover the complete background of the element by stretching or scaling down the image. But here the background image will not maintain its aspect ratio.
Example
background-size:cover
The
cover
value is a mixture of
100% 100%
and
contain
values. In this, the
background-image
will completely cover the element background, and also maintain the aspect ratio of the image. To maintain the aspect ratio, some part of the image may be clipped out.
Example
Media query to set different images for different devices
It’s a good practice to use
@medai
query to set the different images for the different display sizes. For instance, we can set a large image for desktop browsers whose display size is greater than 500px, and a small image for mobile and tablet browsers which screen width is less than 500px.
Example
HTML5 <picture> Element
In HTML5 W3C introduced a new element
<picture>,
that allows us to specify more than one image source. And the user will see that image that will first fit its browser specification.
Example
Summary
- It’s very important to make your images responsive according to the screen display.
- Always use relative values like % to set the length related properties.
- The background of the images also resizes according to the display size.
- The HTML5 <picture> element let you specify more than one image source.