Lazy loading with “responsive” images (unknown height)

前端 未结 4 1216
自闭症患者
自闭症患者 2020-12-28 09:17

I\'m using a CSS grid system which is based upon percentages. I have a grid with 4 columns, each 25% of the page\'s total width. I output my image tags inside of each \"25%

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-28 09:34

    Here's the more elegant solution, from the comments. It still requires writing the aspect ratio server side, but with a wrapper div:

    Then with JS I give the wrapper div a padding-bottom:

    $('div.lazy').livequery(function() {
        var c = $(this);
        var r = c.data('ar');
        c.css('padding-bottom', r * 100 + '%');
    });
    

    This gives the div the exact dimensions that the img will eventually consume. I then use the following LESS to load the image within the area the padding consumes:

    div.lazy {
      max-width:100%;
      position:relative;
      img {
        position:absolute;
        width:100%;
        height:100%;
      }
    }
    

提交回复
热议问题