Adding Style to Your Lazy-Loaded Images

As useful as the Lazy Load ability is, it can be inelegant to have the images just appear suddenly. You can improve upon this with CSS3, and give the loading images a fade-in (or other) effect.

Please note: if the browser does not support CSS3, the following code will be ignored.

The following CSS can be used to create a “fade-in” effect for your lazy-loaded images:

/* PART 1 - Before Lazy Load */
img[data-lazyloaded]{
	opacity: 0;
}

/* PART 2 - Upon Lazy Load */
img.loaded{
	-webkit-transition: opacity .5s linear 0.2s;
	-moz-transition: opacity .5s linear 0.2s;
	transition: opacity .5s linear 0.2s;
	opacity: 1;
}

The key is in the data-lazyloaded attribute selector, which is a method for targeting elements based on their given attributes.

Before an image is lazy loaded, it has the data=“lazyloaded” attribute associated with it, which enables PART 1 of the CSS code.

Once the image is loaded, that attribute goes away, PART 1 is no longer relevant, and PART 2 of the CSS code goes into effect. This example CSS causes the image to fade in, but you can replace the code with any CSS effect you wish.

  • Admin
  • Last modified: 2017/12/18 20:29
  • by Lisa Clarke