简体   繁体   中英

How to render a responsive image in any viewport by keeping aspect ratio?

I have to render images of any size in container which is 90 percent of the viewport. The viewport can have also any size, mobile, tablet, desktop, landscape, portrait, etc. I have to render the image in the container by keeping the aspect ratio but fit in the container, ie. either the height or the width of the image will be the same as of the container.

The solution should be

  • lightweight, no bootstrap and jQuery can be used (zepto.js is OK)
  • no css background image can be used, because all images have a jpg and a webp version and on the real page the picture-source-img HTML structure will be used in place of the img tag
  • independent of the image size and the viewport size, ie. fully responsive

I tried the following simple code, but I don't understand, why the CSS entry object-fit doesn't work and why the image is out of the container on the right side and bottom side if the container is smaller as the image:

<!DOCTYPE html>
<html>
  <head>
    <style>
      .container {
        position: fixed;
        top: 5vh;
        left: 5vw;
        width: 90vw;
        height: 90vh;
      }  
      img {
        object-fit: contain;
        margin: auto;
        display: block;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <img src="https://www.diet-health.info/images/recipes/1400/salatgurke-schlangengurke-cucumber-by-rasbak-at-dutch-wikipedia.jpg">
    </div>
  </body>
</html>

Please have a look to aspect-ratio CSS3 attribute here: https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio

I think this could be a good starting point:

<!DOCTYPE html>
<html>

<head>
    <style>
        .container {
            position: fixed;
            top: 5vw;
            left: 5vw;
            width: 90vw;
            height: 90vh;
        }

        img {
            object-fit: contain;
            margin: auto;
            width: 100%;
            aspect-ratio: 16/9;
        }
    </style>
</head>

<body>
    <div class="container">
        <img
            src="https://www.diet-health.info/images/recipes/1400/salatgurke-schlangengurke-cucumber-by-rasbak-at-dutch-wikipedia.jpg" />

        SEE: https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio
    </div>
</body>

</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM