My Development Notes

Programming Made Easier


How to make images responsive using CSS

To make an image responsive, all you need to do is to set the image width in terms of percentage rather than pixels. Let me demonstrate this with an example :

<body>
   <h1>This is a responsive image</h1>
   <img src="./image_file.jpg" alt="image"> 
</body>

Say, we have an image called image_file.jpg in the HTML file. All we need is to go to the CSS file and set the image width in percentage instead of pixel or the like so:

img {
    width: 100%;
}

Doing this will make the image work responsively, which means the image will scale up or down in the correct proportion, depending upon the screen size. However, setting the img tag will work proportionately with respect to the parent container, which, in the above case is the body. So here, the width of the img tag is 100% of its parent container (i.e, the body in this case).

Note : Make sure you only set the percentage of the width and not the height for this method to work correctly. If you set both the width and height properties the image might get distorted.


Posted

in

by

Tags:

Leave a Reply