Hi there! Love the idea of using gatsby-image for image optimization & lazy loading.
I've got a hero image coming in from Contentful that stretches across a fluid container. My query is pretty simple: sizes(maxWidth: 1600) { ...GatsbyContentfulSizes }
However, I need to art direct this image a bit on smaller breakpoints. If I were using a standard srcset, I would want my sizes to look something like this: sizes="(min-width: 768px) 100vw, (min-width: 375px) 250vw, 400vw"
Is there any way to leverage gatsby-image with custom sizes? I can build my own sizes and srcSet values, I just need a way to push them into the gatsby-image component.
gatsby-image accepts sizes prop that’s shaped like the following object:
{
aspectRatio: 1.5,
base64: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAZABkAAD...",
sizes: "(max-width: 880px) 100vw, 880px"
src: "//images.ctfassets.net/.../slide_1.jpg?w=880&q=50"
srcSet: "//images.ctfassets.net/.../slide_1.jpg?w=220&h=76&q=50 220w,\n//images.ctfassets.net/.../slide_1.jpg?w=440&h=151&q=50 440w,\n//images.ctfassets.net/.../slide_1.jpg?w=880&h=303&q=50 880w,\n//images.ctfassets.net/.../slide_1.jpg?w=980&h=337&q=50 980w"
}
Let’s say your sizes comes from a query as follows:
heroImage {
sizes(maxWidth: 880) {
...GatsbyContentfulSizes
}
}
You can build your own sizes and srcSet and override the values returned by the GraphQL query by doing:
const sizes = YOUR_SIZES_HERE
const srcSet = YOUR_SRCSET_HERE
const overriddenHeroImageSizes = { ...heroImage.sizes, sizes, srcSet }
return (
<GatsbyImg sizes={overriddenHeroImageSizes} />
)
Working like a charm @ryanditjia. Thanks!
May be useful to add this approach to the docs.
Personnaly, I like declaring breakpoints and maxWidth using the srcSetBreakpoints parameter from gatsby-plugin-sharp. The documentation well explained how to setup.
heroImage {
childImageSharp {
fluid(maxWidth: 1920, srcSetBreakpoints: [ 400, 600, 960, 1280, 1920 ] ) {
src
srcSet
sizes
}
}
}
I am using srcSetBreakpoints: [400] with the intention of having gatsby-plugin-sharp generate only:
But the images generated continue to include other breakpoints. For example the fluid.srcSet attribute for one of my image includes 400px, 800px, 1600px.
If I change to srcSetBreakpoints: [320], now I get 320px, 800px, 1600px. Seems that changing srcSetBreakpoints does affect fluid.srcSet, but doesn't limit it to export larger version of the image.
My reason is I have a large site with thousands of images and Netlify wouldn't build it because it's compose of too many files with error Error: ENOSPC: System limit for number of file watchers reached. I wanted to try to reduce the quantity of image copies generated to see if I could make it fit.
Most helpful comment
Personnaly, I like declaring breakpoints and maxWidth using the
srcSetBreakpointsparameter from gatsby-plugin-sharp. The documentation well explained how to setup.