Set width/height of image to avoid reflow on image load

后端 未结 6 1796
甜味超标
甜味超标 2020-12-30 23:00

When I use image tags in html, I try to specify its width and height in the img tag, so that the browser will reserve the space for them even before the images

6条回答
  •  时光取名叫无心
    2020-12-30 23:34

    If I understand the requirements ok, you want to be able to set an image size, where this size is known only on content (HTML) generation, so it can be set as inline styles.

    But this has to be independent of the CSS, and also prior to image loading, so also independent from this image sizes.

    I have come to a solution tha involves wrapping the image in a div, and including in this div an svg that can be set to have proportions directly as an inline style.

    Obviously this is not much semantic, but at least it works

    The containing div has a class named img to show that it , well, should be an img

    To try to reproduce the loading stage, the images have a broken src

    .container {
      margin: 10px;
      border: solid 1px black;
      width: 200px;
      height: 400px;
      position: relative;
    }
    
    .img {
      border: solid 1px red;
      width: fit-content;
      max-width: 100%;
      position: relative;
    }
    
    svg {
      max-width: 100%;
      background-color: lightgreen;
      opacity: 0.1;
    }
    
    #ct2 {
      width: 500px;
    }
    
    .img img {
      position: absolute;
      width: 100%;
      height: 100%;
      max-height: 100%;
      max-width: 100%;
      top: 0px;
      left: 0px;
      box-shadow: inset 0px 0px 10px blue;
    }

提交回复
热议问题