F
F
Fedooot012021-03-14 22:05:29
css
Fedooot01, 2021-03-14 22:05:29

How to scale an image to fit max-width and max-height while maintaining aspect ratio?

Hello, there is a task to increase the image to the specified max-width or max-height while maintaining the proportions. For example:

img {
  display: block;
  max-width: 400px;
  max-height: 200px;
}

And given an image 800 pixels wide and 100 pixels high, it should eventually fit within the constraints and become 400 pixels wide and 50 high. Or given an image 100 pixels wide and 150 pixels high, it should end up being 133 pixels high and 200 wide. In the case, when the image dimensions are larger than max-width or max-height, it scales appropriately. Implementation example When an image falls short of, for example, the size limits, it naturally does not scale, although this should be done. Adding to img only breaks the proportions. How to do all this right?
<img src="https://loremflickr.com/800/100">

<img src="https://loremflickr.com/100/150">



width: 100%; height: auto;

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question