Set image width / height to avoid image overflow

When I use image tags in html, I try to specify its width and height in the img tag so that the browser leaves space for them even before loading the images, so when they finish loading, the page does not overpay (elements do not move). For instance:

 <img width="600" height="400" src="..."/> 

The problem now is that I want to create a more “responsive” version, where for the “single-column case” I would like to do this:

 <img style="max-width: 100%" src="..."/> 

but if I mix this with an explicit width and height, for example:

 <img style="max-width: 100%" width="600" height="400" src="..."/> 

and the image is wider than the available space, then the image changes without ignoring the proportion. I understand why this happens (because I "fixed" the height of the image), and I would like to fix it, but I have no idea how to do this.

To summarize: I want to specify max-width: 100% , and also somehow make sure that the content is not rescheduled when loading images.

+4
source share
2 answers

I am also looking for an answer to this problem. With max-width , width= and height= browser has enough data so that it can leave the right space for the image, but it just doesn't work that way.

I worked on this with a jQuery solution. It requires you to have width= and height= for the <img> tags.

CSS

 img { max-width: 100%; height: auto; } 

HTML:

 <img src="image.png" width="400" height="300" /> 

JQuery

 $('img').each(function() { var aspect_ratio = $(this).attr('height') / $(this).attr('width') * 100; $(this).wrap('<div style="padding-bottom: ' + aspect_ratio + '%">'); }); 

This automatically applies the technique shown in: http://andmag.se/2012/10/responsive-images-how-to-prevent-reflow/

+3
source

for responsive html wrap the image with a div only the width of the div.

CSS

 .imgPan{ width:200px; } .imgPan img{ max-width:100%; height:auto; } 

HTML

 <div class="imgPan"> <img src="..."/> </div> 

Now the image will change in proportion.

-3
source

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


All Articles