There is a picture with the given parameters width and height . Dimensions are set so that after uploading the image the layout does not 'jump'.

 <img src="photo.jpg" width="900" height="400" class="photo"> 

How to make a responsive picture correctly? The problem is that if you add height: auto; max-width: 100%; height: auto; max-width: 100%; then the width and height attributes are simply ignored and the picture starts jumping.

That is, I want the picture to be in proportion to the width and height values, but at the same time it changes to fit the screen.

Perhaps this can be implemented using the css calc function?

    2 answers 2

    It is necessary to wrap the picture in a responsive-block, preserving the desired proportions.
    To do this, we use the fact that vertical indents are calculated from the width.

     figure { margin: 0; overflow: hidden; } figure:before { content: ""; float: left; padding-top: 44.444%; } img { display: block; max-width: 100%; } 
     before image <figure> <img src="//i.stack.imgur.com/BXz9J.jpg"> </figure> after image 

    • Why 44.444%? (I know, but other visitors are not a fact} - andreymal
    • @andreymal 400/900 = 44.444% - Qwertiy
    • Thanks Qwertiy and @andreymal. Without clarification about 44.444 I would not understand. Perhaps it should be explained in the answer itself? - user2168735 pm
    • @ user2168735, added. - Qwertiy
     <div class="img"><img src="" alt=""></div> .img{ max-width: 600px; max-height: 400px; } .img img{ width: 100%; height: 100%; object-fit: cover; } 
    • Hey. It does not work for me - output.jsbin.com/haxireximi - user2168735
    • corrected, checked - Roman Kh.
    • there is the same problem as with height: auto; max-width: 100%; While the picture is not loaded, the height of the img 18px block. You can set the background-color: red; for .img and through the inspector to remove the src attribute. - user2168735