My Development Notes


How to Scale Image without distorting the aspect ratio using CSS


Here’s a simple web page with a dog photo :

<html>
     <body>
           <img src="./dog_photo.jpg" alt="a dog">
     </body>
      
</html>

Say the image dog_photo.jpg is huge, around 4500 X 2200 pixels in size, and falls off the container. You just have to change the height or width to a smaller size. Remember, height OR width, not both of them. If you change both, the image gets distorted.

Ideally if the image is in portrait mode, it’s better to change the width and, if it’s in landscape then you should only change the height.

Method 1

Here’s the example:

img {
     width : 2200px;
}

So, only change either the image width or height, and not both so that it doesn’t get distorted and look ugly. This way the proper aspect ratio is maintained.

Method 2

img {
    width : 2200px;
    height: auto;
}

Here, we’ve set the height to ‘auto’. However this method is not a requirement, it’s just another way to do it.


Leave a Reply

Your email address will not be published. Required fields are marked *