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

后端 未结 6 1909
甜味超标
甜味超标 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:30

    For a css only solution, you can wrap the img in a container where the padding-bottom percentage reserves space on the page until the image loads, preventing reflow.

    Unfortunately, this approach does require you to include the image aspect ratio in your css (but no need for inline styles) by calculating (or letting css calculate for you) the padding-bottom percentage based on the image height and width.

    If many of your images can be grouped into a few standard aspect ratios, then you could create a class for each aspect ratio to apply the appropriate padding-bottom percentage to all images with that aspect ratio. This may save you a little time and effort if you are not dealing with a wide variety of image aspect ratios.

    Following is some example html and css for an image with a 2:1 aspect ratio:

    HTML

    CSS

    .container {
      display: block;
      position: relative;
      padding-bottom: 50%; /* calc(100%/(300/150)); */
      height: 0;
    }
    
    .container img {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }
    

    The snippet below adds some extra html, css and javascript to create some visual top and bottom reference points and mimic a very slow loading image so you can visually see how the reflow is prevented with this approach.

    const image = document.getElementById('image');
    const source = 'https://via.placeholder.com/300x150';
    const changeSource = () => image.src = source;
    
    setTimeout(changeSource, 3000);
    .container {
      display: block;
      position: relative;
      padding-bottom: 50%; /* calc(100%/(300/150)); */
      height: 0;
    }
    
    .container img {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }
    
    .top, .bottom {
      background-color: green;
      width: 100%;
      height: 20px;
    }

提交回复
热议问题