Using the LazySizes plugin (https://github.com/aFarkas/lazysizes) I'm trying to build a grid of images, each with an alternate version for smaller viewports. The grid (container) is a simple column/row based percentage based layout.
I'm not quite sure how to declare the images, I keep seeing only the larger versions. I've opted for using high-res images and scaling them down 50% with a max width for the container. Here's a markup sample of the the images:
<img data-sizes="(min-width: 320px) 100vw, (min-width: 768px) 100vw"
data-src="images/grid/image-small.jpg"
data-srcset="images/grid/image-small.jpg 720w, images/grid/image-big.jpg 1440w"
alt="" class="lazyload" />
I only need one breakpoint which is at 768px. The confusing part is the data-sizes attribute. Should I be declaring another size here since the images are high-res or should I just let them have full width?
Added: The generated markup I get when the script initiates:
<img data-sizes="(min-width: 320px) 100vw, (min-width: 768px) 1440px"
data-src="images/grid/image-small.jpg"
data-srcset="images/grid/image-small.jpg720w, images/grid/image-big.jpg 1440w"
alt="" class=" lazyloaded"
sizes="(min-width: 320px) 100vw, (min-width: 768px) 1440px"
srcset="images/grid/image-small.jpg 720w, images/grid/image-big.jpg 1440w"
src="images/grid/image-small.jpg">
srcset
spec author here.
Well, your current sizes
attribute is useless; it just specifies the same size for both breakpoints, and both of them are just specifying the default size anyway.
Why are you trying to do some weird sizing hack? You'll be fighting against what the <img>
is trying to do, so whatever you end up with will be hacky.
Just follow the spec: sizes
should declare how large the image will be in the page (this defaults to 100vw
already, so you can omit it if you already plan on the image being full-width). You can use MQs here if you're doing responsive design and your different layouts need to size the image differently, but if it'll always be the same size, don't complicate things.
Then just declare how large your image is in the `srcset. It looks like you're already doing that, so that's good (assuming that your images really are 720 and 1440 image-pixels wide). The browser will pick the image it wants based on that information.
I'm not 100% sure on how you're planning to use the image, but it sounds like you might be planning on displaying the images as half the width of the screen? In that case, just use sizes=50vw
and everything will take care of itself.
(I have no idea how LazySizes works, so if it's doing something weird I can't help you with that.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With