1

I have 3 different layouts for a design I completed in Sketch. Each design has a header image as can be seen below:

enter image description here

On different devices, I load a different image to keep the height in check and crop the image. When I export from Sketch I have the following images:

dog-header-mobile-1x.png
dog-header-mobile-2x.png
dog-header-mobile-3x.png
dog-header-mobile-4x.png

dog-header-tablet-1x.png
dog-header-tablet-2x.png
dog-header-tablet-3x.png
dog-header-tablet-4x.png

dog-header-desktop-1x.png
dog-header-desktop-2x.png
dog-header-desktop-3x.png
dog-header-desktop-4x.png

I'd like to load the 1x, 2x, 3x and 4x images where appropriate. But what's confusing me is I have 3 different images for the 3 devices so do I need to use srcset AND sizes to achieve this? It seems like a very long-winded way to do this and I'm pretty sure I'm doing it wrong.

BugHunterUK
  • 8,346
  • 16
  • 65
  • 121

2 Answers2

1

Have you tried out media queries? You can define the size when you want to use mobile, tablet or desktop version. There you can also set a different background-image for your header-image.

https://wiki.selfhtml.org/wiki/CSS/Media_Queries

https://www.w3schools.com/css/css_rwd_mediaqueries.asp

Alex Berger
  • 1,357
  • 1
  • 10
  • 22
  • Can CSS load images based on pixel density/device? – BugHunterUK Jan 07 '18 at 17:52
  • Ah, I found `min-resolution` with media queries. Thankfully `autoprefixer` takes care of vendor prefixes. Many thanks. Although this wasn't the solution, it was helpful in helping me find a solution. – BugHunterUK Jan 07 '18 at 17:58
  • 1
    @BugHunterUK you can set media queries for different pixel ratio with "device-pixel-ration", so I guess yes, it should be possible. Maybe the following link can help you https://css-tricks.com/snippets/css/retina-display-media-query/ – Alex Berger Jan 07 '18 at 17:59
1

You can use the <picture> element.

<picture>
    <source
        media="(max-width: 740px)"
        srcset="
            dog-header-mobile-1x.png,
            dog-header-mobile-2x.png 2x,
            dog-header-mobile-3x.png 3x,
            dog-header-mobile-4x.png 4x">
    <source
        media="(max-width: 1440px)"
        srcset="
            dog-header-tablet-1x.png,
            dog-header-tablet-2x.png 2x,
            dog-header-tablet-3x.png 3x,
            dog-header-tablet-4x.png 4x">
    <source
        srcset="
            dog-header-desktop-1x.png,
            dog-header-desktop-2x.png 2x,
            dog-header-desktop-3x.png 3x,
            dog-header-desktop-4x.png 4x">

    <img src="dog-header-desktop-1x.png" alt="Dog">
</picture>

IE doesn't support it, but will fallback to the default img element.

m.spyratos
  • 3,823
  • 2
  • 31
  • 40