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

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

    At first I would like to write about the answer from october 2013. This was incomplete copied and because of them it is not correct. Do not use it. Why? We can see it in this snippet (scroll the executed snippet to the bottom):

    $('img').each(function() { 
        var aspect_ratio = $(this).attr('height') / $(this).attr('width') * 100;
        $(this).wrap('
    '); });
    img { max-width: 100%; height: auto; }
    
    
    Some text

    And we can see the text is afar from bottom. What is in this example incomplete/ incorrect? I will show it with correct example with pure JavaScript (we do not need to download jQuery for that).

    Correct example with pure JavaScript

    Please scroll the executed snippet to the bottom.

    var imgs = document.querySelectorAll('img');
    for(var i = 0; i < imgs.length; i++)
    {
        var aspectRatio = imgs[i].getAttribute('height') /
                          imgs[i].getAttribute('width') * 100;
    
        var div = document.createElement('div');
        div.style.paddingBottom = aspectRatio + '%';
        imgs[i].parentNode.insertBefore(div, imgs[i]);
        div.appendChild(imgs[i]);
    }
    .restrict-container div{position:relative}
    img
    {
        position:absolute;
        max-width:100%;
        top:0; left:0;
        height:auto
    }
    Some text
    Some text

    The mistake from answer from october 2013: the image should be placed absolute (position:absolute) to the wrapped container but it is not so placed.

    This is the end of my answer to this question.


    For further information read more about:

    • What could we do with the new HTML5 technology for responsive images too? (this is previous extended version of my posting here. See there the second part).

提交回复
热议问题