Picturefill 2 IMG height jumps on page load

135 Views Asked by At

When using Picturefill 2 I'm getting layout jumping on images while the page is loading, for example, when you don't specify height on a normal image. Is this expected with Picturefill and is there a way around this problem? Thanks.

1

There are 1 best solutions below

1
On

The problem you are describing isn't necessarily limited to Picturefill. To avoid this issue you can calculate the ratio of the image’s height to its width. Even with loading images for a responsive site, though you may not know the image dimensions because of screen size, this ratio will be the same. For example, for a height of 200px and width of 300px:

200px / 300px * 100 = 66.66666667

Create a container div around the Picturefill element(s)

<div class="image-container">
   <picture>
     <source srcset="examples/images/extralarge.jpg" media="(min-width: 1000px)">
     <source srcset="examples/images/art-large.jpg" media="(min-width: 800px)">
     <img srcset="examples/images/art-medium.jpg" alt=" ">
    </picture>
</div>

And use the following CSS

.image-container {
  position: relative;
  padding-bottom: 66.66666667%; /* ratio of image height to width */
  height: 0;
  overflow: hidden;
}

.image-container img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
}

That should work. Check out this blog post and this CodePen example for more info.

EDIT

This method doesn't work if the ratios of the image widths and heights are different for responsive image loading. I just ran into this situation so just a heads up.