Automatically resize images to proportions but not stretch

I want to resize the image based on the size of the screen, but I do not want this image to exceed its executive pixels when the screen is too large. So far i have managed to do this

<div align="center" style="position:static; height: 100%; width: 100%; top:0;left 0;"> <img src="myImg.png" style="width: 80%"> </div> 

This maintains the aspect ratio I want, but when the screen is too big, it also stretches the image. I do not want it.

+6
source share
3 answers

Css for a sensitive image is as follows:

  max-width: 100%; height: auto; 

This will reduce the size of the image with the size of its container without exceeding the natural width of the image. However, using width: 100%; make the image be as wide as its container, regardless of the actual size of the image.

A few other notes:

  • align="center" out of date. You must use css to align the content, so text-align: center; .
  • Using position: static; not required since this is the default value for the position property. The only time I can think about where you should use this is if you need to override some other css.
  • If you are not completely positioning your div (which you are not), then top: 0; left: 0; top: 0; left: 0; will do nothing.

Without seeing the rest of the code, I think this would be the best solution for what you are trying to execute:

  <div style="text-align: center;"> <img src="myImg.png" style="max-width: 100%; height: auto;" alt="FYI, image alt text is required" /> </div> 
+11
source

If you also set the max-width attribute, it will limit the size of the image. So:

 <div align="center" style="position:static; height: 100%; width: 100%; top:0;left 0;"> <img src="myImg.png" style="width: 80%; max-width: 300px;"> </div> 

You can make this max-width any size you want if it does not exceed the actual width of the image. Also possible with height.

+2
source
 class="img-thumbnail" 

may be a solution.

-7
source

Source: https://habr.com/ru/post/988588/


All Articles