Languages

CSS - force image resize keeping aspect ratio

3 points
Asked by:
Isaiah89
751

I have a problem working with images with their aspect ratio.

For example:

<img src="image.jpg" width="400" height="200" alt="" />

Its height and width are already specified and now I want to add a CSS rule for images:

img {
    max-width: 300px;
}

But for my image.jpg, I get width=300 and height=200.

How can I set images to be resized keeping their aspect ratios?

1 answer
3 points
Answered by:
Isaiah89
751

The following CSS should solve your problem:

img {
    display: block;
    max-width: 300px;
    max-height: 100px;
    width: auto;
    height: auto;
}

 

Practical example

The image inside the body is originally 225x225 pixels, but it is resized by the CSS to 100px height keeping aspect ratio (it means 100x100).

// ONLINE-RUNNER:browser;

<!DOCTYPE html>
<html>
<head>
  <style>

    img {
        display: block;
        max-width: 250px;
        max-height: 100px;
        width: auto;
        height: auto;
    }

  </style>
</head>
<body>
  <img height="225" width="225" src="https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png" />
</body>
</html>
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join