Images in CSS with background

Use @media queries. Using a mobile-first perspective, your CSS media queries should be: min-width.

    .image-background {
      width: 100%;
      height: 100vh;
      background-size: cover;
      background-position: center center;
      background-image: url('/images/mobile/forest.jpg');
    }

    @media screen and (min-width: 768px) {
      .image-background {
        background-image: url('/images/desktop/forest.jpg');
        background-size: cover;
      }
    }

    @media screen and (min-width: 1200px) {
      .image-background {
        background-image: url('/images/large-desktop/forest.jpg');
        background-size: cover;
      }
    }

 

Images in HTML with <picture>

Use the <picture> element for HTML media queries.

  <picture class="picture">
    <source srcset="/images/large-desktop/forest.jpg" media="(min-width:1200px)">
    <source srcset="/images/desktop/forest.jpg" media="(min-width:768px)">
    <source srcset="/images/mobile/forest.jpg" media="(min-width:0)">
    <img srcset="/images/desktop/forest.jpg" src="/images/desktop/forest.jpg" alt="See the forest through the trees">
  </picture>

 

Images with JavaScript (LazyLoading)

When it comes to mobile-to-desktop, there are tried and true solutions you will want to use in order to make sure that the end user is only getting the images they need for their specific experience. By specifically targeting this way, you can ensure that your mobile users get the smallest images possible and your desktop users get amazing hi resolution images.

Lazy Loading

Lazy loading means only load images when the user comes close to requesting them by scrolling down the page

Usage
  1. Use lazyload JavaScript library (consider that it is 500kb in size, and see if that’s feasible to your Perfromance Budget).
  2. Include the lazyload.min.js file in your HTML at the bottom of the <body> element.
  3. Initialize lazyload() object.
    Optional: Reconfigure scrolling threshold value to suit your project & image sizes.
  <script src="/js/lazyload.min.js"></script>
  <script>
    var myLazyLoad = new LazyLoad({
        threshold: 1472,
    });

    //new LazyLoad();
  </script>
  1. Replace src attribute of images with data-original .
  <div>
    <img data-original="/images/18.jpg" width="414" height="736">
    <img data-original="/images/19.jpg" width="414" height="736">
    <img data-original="/images/20.jpg" width="414" height="736">
  </div>