Understanding gatsby-image (Part 3): Controlling sizes, breakpoints and styling

This is Part 3 of a three-part series covering the Gatsby plugin gatsby-image
Part 1:
Graphql, generated files & markup
Part 2: Responsive images 101
Part 3: Controlling src-set, breakpoints and styling

Gatsby Image: What src-set property does it generate?

"srcSet": 
"/static/1234/1111/my-image.jpg 600w,
/static/1234/2222/my-image.jpg 900w”

In the case of a fluid image it is producing a src-set with an x-descriptor appended to each source (e.g. 1.5x)

"srcSet": 
"/static/1234/1111/my-image.jpg 1x,
/static/1234/2222/my-image.jpg 1.5x,
/static/1234/3333/my-image.jpg 2x”

Gatsby Image: What sizes property does it generate?

Gatsby image just takes the sizes property from what gatsby-plugin-sharp is outputting. Remember, in Part 1 we showed how the fragment “GatsbyImageSharpFluid” includes a “size” property.

If you haven’t indicated a maxWidth in your graphql query it will generate:

sizes="(max-width: 800px) 100vw, 800px"

If you have indicated a maxWidth of 1200px, it will look like this:

sizes="(max-width: 1200px) 100vw, 1200px"

You can see here that the 100vw is based on the assumption that your image will take up the full available viewport width. It doesn’t take into account that your full-width image might be smaller because it’s living in a container with paddings and margins. So what can you do?

Setting custom sizes and breakpoints

<Img
fluid={{
...img.image,
sizes: "(max-width: 1200px) calc(100vw - 40px), 1200px",
}}
/>

This way you don’t load images that are much bigger than what you really need. You might also want to override the sizes property to add additional breakpoints:

sizes: "(max-width: 300px) calc(100vw - 20px), (max-width: 600px) calc(100vw - 40px), 1200px",

Another technique for overriding sizes is to include your custom sizes as a query parameter in your graphql query, like in this example:

childImageSharp { 
fluid(sizes: “(max-width: 1200px) calc(100vw - 40px), 1200px”){
...GatsbyImageSharpFluid
}
}

Controlling which image sizes are generated

Checkout the documentation of gatsby-plugin-sharp here: https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby-plugin-sharp#parameters-2

Ways to style/layout the image created by gatsby-image

The <Image/> component from gatsby-image accepts the following properties related to styling:

style={} /* styles for the wrapper container */
imgStyle={} /* Styles for the actual img element */

Here’s an interesting discussion of how to apply custom styling to a gatsby image.

👉 That was the 3-part series about gatsby-image. I hope it was helpful!

A mix of Frontend Development, Machine Learning, Musings about Creative AI and more