Home > Software design >  There is an alternative at source tag to deliver media base on screen size using CSS property backgr
There is an alternative at source tag to deliver media base on screen size using CSS property backgr

Time:08-18

I want to deliver the lighter image as possible for my website. To accomplish that, usually use source with that sort of HTML code :

<picture>
    <source
      srcset="assets/images/compressed/litopia-s4-256.avif"
      media="(max-width: 512px)"
      type="image/avif"
    />
    <source
      srcset="assets/images/compressed/litopia-s4-512.avif"
      media="(max-width: 1024px)"
      type="image/avif"
    />
    <source
      srcset="assets/images/compressed/litopia-s4-1024.avif"
      media="(max-width: 2048px)"
      type="image/avif"
    />
    <!-- webp -->
    <source
      srcset="assets/images/compressed/litopia-s4-256.webp"
      media="(max-width: 512px)"
      type="image/webp"
    />
    <source
      srcset="assets/images/compressed/litopia-s4-512.webp"
      media="(max-width: 1024px)"
      type="image/webp"
    />
    <source
      srcset="assets/images/compressed/litopia-s4-1024.webp"
      media="(max-width: 2048px)"
      type="image/webp"
    />
    <!-- jpeg -->
    <source
      srcset="assets/images/compressed/litopia-s4-256.jpg"
      media="(max-width: 512px)"
      type="image/jpeg"
    />
    <source
      srcset="assets/images/compressed/litopia-s4-512.jpg"
      media="(max-width: 1024px)"
      type="image/jpeg"
    />
    <source
      srcset="assets/images/compressed/litopia-s4-1024.jpg"
      media="(max-width: 2048px)"
      type="image/jpeg"
    />
    <img src="/assets/images/litopia-port-s4.png" alt="Litopia Season 4">
</picture>

And I would like to know if there is something similar when I intend to deliver an image using background-image in CSS

like this :

.bg-img{
  background-image: url("/assets/images/litopia-s4.png");
  background-size:cover;
}

CodePudding user response:

You can definitely do that with media queries :

@media (max-width: 1024px) {
  .bg-img{
     background-image: url("/assets/images/litopia-s4-512.png");
     background-size:cover;
  }
}
@media (max-width: 512px) {
  .bg-img{
     background-image: url("/assets/images/litopia-s4-256.png");
     background-size:cover;
  }
}

Pay attention to the sequential order of Media Queries : it matters. (from the highest to lowest resolution)

Edit

Didn't see @Kaiido comment before posting. But yeah, to check if your media format is handle, Modernizr would be the way to go I think.

  • Related