• Zachariah
    link
    fedilink
    arrow-up
    16
    ·
    22 days ago

    tldr…

    Don’t use this:

    <div class="image-wrapper">
      <img class="image--desktop"
        src="/image-desktop.jpg" 
        width="1200" height="400"
        alt="Super descriptive text">
      <img class="image--mobile" 
        src="/image-mobile.jpg" 
        width="600" height="800"
        alt="Super descriptive text">
    </div>
    

    and:

    .image--desktop {
      display: none;
    }
    @media (min-width: 1200px) {
      .image--mobile {
        display: none;
      }
      .image--desktop {
        display: block;
      }
    }
    

    Instead of all that duplicate HTML and unnecessary CSS, all you need is this [HTML and no CSS or JavaSctipt]

    <div class="image-wrapper">
      <picture>
        <source 
          src="/desktop-image.jpg" 
          width="1200" height="400"
          media="min-width: 1200px">
        <source
          src="/mobile-image.jpg" 
          width="600" height="800"
          media="max-width: 1199px">
        <img src alt="Super descriptive text">
      </picture>
    </div>
    
    • refalo@programming.dev
      link
      fedilink
      arrow-up
      4
      ·
      22 days ago

      You can’t style the sources differently, but you can with img tags.

      Also the picture element is less than ten years old.

      • codeinabox@programming.devOP
        link
        fedilink
        English
        arrow-up
        2
        ·
        21 days ago

        You can’t style the sources differently, but you can with img tags.

        Could you achieve the same thing with media queries?

        Also the picture element is less than ten years old.

        According to caniuse, since March 2016 it works across the latest devices and major browser versions. So it depends if you have users with very old browsers or devices.

        • refalo@programming.dev
          link
          fedilink
          arrow-up
          1
          ·
          21 days ago

          Could you achieve the same thing with media queries?

          Not always. Suppose you wanted different sets of colors (per source) on mobile vs desktop where the screen/media size was irrelevant, you’d need a way to attach classes to individual source elements, but they don’t accept classes.

          it depends if you have users with very old browsers or devices

          I was more mentioning that because of developers not always using the latest browser features.

    • nebeker@programming.dev
      link
      fedilink
      English
      arrow-up
      3
      ·
      22 days ago

      Thanks for the TLDR! That looks very clean and handy. I like how HTML is slowly evolving to do more of the simple stuff we need.

      You accidentally replaced the alt with another arc. I bet it’ll still work, to be honest. HTML parsing is so widely lax.