Gathering detailed insights and metrics for gatsby-background-image-es5
Gathering detailed insights and metrics for gatsby-background-image-es5
Gathering detailed insights and metrics for gatsby-background-image-es5
Gathering detailed insights and metrics for gatsby-background-image-es5
Lazy-loading React (multi)background-image component with optional support for the blur-up effect.
npm install gatsby-background-image-es5
Typescript
Module System
Node Version
NPM Version
JavaScript (86.95%)
TypeScript (8.43%)
CSS (3.98%)
Shell (0.64%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
252 Stars
914 Commits
49 Forks
5 Watchers
12 Branches
23 Contributors
Updated on Mar 30, 2025
Latest Version
1.6.0
Package Id
gatsby-background-image-es5@1.6.0
Unpacked Size
100.33 kB
Size
23.47 kB
File Count
21
NPM Version
lerna/4.0.0/node@v14.17.0+x64 (linux)
Node Version
14.17.0
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
6
Speedy, optimized background-images without the work!
gatsby-background-image-es5
is a React component which for background-images
provides,
what Gatsby's own gatsby-image
does for the rest of your images.
This version is completely transpiled to ES5 to target older browsers like IE11!
Most polyfills are already built in, though this nearly triples the package size
compared to gatsby-background-image
!
Everything else just works the same as in gatsby-background-image
, so it
provides for background-images, what Gatsby's own gatsby-image
does for the
rest of your images and even more:
Testing explained in its own section.
Art-Direction support built in.
It has all the advantages of gatsby-image,
including the "blur-up" technique or a "traced placeholder"
SVG to show a preview of the image while it loads,
plus having AVIF support (with the help of gbimage-bridge)!
plus being usable as a container (no more hacks with extra wrappers)
plus being able to work with multiple stacked background images
plus being able to style with Tailwind CSS and suchlike Frameworks
All the glamour (and speed) of gatsby-image
for your Background Images!
Of course styleable with styled-components
and the like!
For usage with Gatsby 3+4's gatsby-plugin-image
see:
Gatsby 3+4 & gatsby-plugin-image!
gatsby-background-image
gatsby-background-image
has an example repository to see its similarities &
differences to gatsby-image
side by side.
It's located at: gbitest
To use it with gatsby-background-image-es5
change the dependency there.
As gatsby-image
is designed to work seamlessly with Gatsby's native image
processing capabilities powered by GraphQL and Sharp, so is gatsby-background-image-es5
.
To produce optimized background-images, you need only to:
gatsby-background-image-es5
and use it in place of the built-in div
or suchlike containers.gatsby-transformer-sharp
gatsby-background-image-es5
.The GraphQL query creates multiple thumbnails with optimized JPEG and PNG
compression (or even WebP files for browsers that support them).
The gatsby-background-image-es5
component automatically sets up the
"blur-up" effect as well as lazy loading of images further down the screen.
To add gatsby-background-image-es5
as a dependency to your Gatsby-project use
1npm install --save gatsby-background-image-es5
or
1yarn add gatsby-background-image-es5
Depending on the gatsby starter you used, you may need to include gatsby-transformer-sharp and gatsby-plugin-sharp as well, and make sure they are installed and included in your gatsby-config.
1npm install --save gatsby-transformer-sharp gatsby-plugin-sharp
or
1yarn add gatsby-transformer-sharp gatsby-plugin-sharp
Then in your gatsby-config.js
:
1plugins: [`gatsby-transformer-sharp`, `gatsby-plugin-sharp`]
Also, make sure you have set up a source plugin, so your images are available in
graphql
queries. For example, if your images live in a project folder on the
local filesystem, you would set up gatsby-source-filesystem
in
gatsby-config.js
like so:
1const path = require(`path`) 2 3module.exports = { 4 plugins: [ 5 { 6 resolve: `gatsby-source-filesystem`, 7 options: { 8 name: `images`, 9 path: path.join(__dirname, `src`, `images`), 10 }, 11 }, 12 `gatsby-plugin-sharp`, 13 `gatsby-transformer-sharp`, 14 ], 15}
With gatsby-background-image(-es5)
@ v0.8.8
it's now possible to use
Tailwind CSS classes like md:w-1/2
to style BackgroundImage
.
Therefore a specialChars
plugin option has been introduced to be able to
properly escape such classes, which defaults to :/
but may be set to other
characters in gatsby-config.js
like the following:
1module.exports = { 2 plugins: [ 3 ... 4 { 5 resolve: 'gatsby-background-image-es5', 6 options: { 7 // add your own characters to escape, replacing the default ':/' 8 specialChars: '/:', 9 }, 10 }, 11 ... 12 ], 13};
If you support Safari and/or Internet Explorer, you have to use the
IntersectionObserver
polyfill.
As - at the time of writing - neither fully implements the feature
(see caniuse.com).
This is already the ES5 version of gatsby-background-image
, so nothing easier
than that! Just add gatsby-background-image-es5
as a plugin to your
gatsby-config.js
like this:
1module.exports = { 2 plugins: [ 3 ... 4 `gatsby-background-image-es5`, 5 ... 6]
For the moment, until the next major version for gatsby-background-image
, the
new syntax of image queries is only supported through a companion package called
gbimage-bridge
. Head over to its
README
to learn more, but here a TLDR installation instruction:
1yarn add gbimage-bridge
or
1npm install --save gbimage-bridge
and usage with BackgroundImage
is as follows:
1import React from 'react' 2import { graphql, useStaticQuery } from 'gatsby' 3import { getImage, GatsbyImage } from "gatsby-plugin-image" 4 5import { convertToBgImage } from "gbimage-bridge" 6import BackgroundImage from 'gatsby-background-image' 7 8const GbiBridged = () => { 9 const { placeholderImage } = useStaticQuery( 10 graphql` 11 query { 12 placeholderImage: file(relativePath: { eq: "gatsby-astronaut.png" }) { 13 childImageSharp { 14 gatsbyImageData( 15 width: 200 16 placeholder: BLURRED 17 formats: [AUTO, WEBP, AVIF] 18 ) 19 } 20 } 21 } 22 ` 23 ) 24 const image = getImage(placeholderImage) 25 26 // Use like this: 27 const bgImage = convertToBgImage(image) 28 29 return ( 30 <BackgroundImage 31 Tag="section" 32 // Spread bgImage into BackgroundImage: 33 {...bgImage} 34 preserveStackingContext 35 > 36 <div style={{minHeight: 1000, minWidth: 1000}}> 37 <GatsbyImage image={image} alt={"testimage"}/> 38 </div> 39 </BackgroundImage> 40 ) 41} 42export default GbiBridged
But gbimage-bridge
has also a BgImage
wrapper component for this, so read
more over there ; )!
Be sure to play around with the Example Repo, as it shows
a few more flavors of using BackgroundImage
, e.g. encapsulating it in a
component : )!
This is what a component using gatsby-background-image-es5
might look like:
1import React from 'react' 2import { graphql, useStaticQuery } from 'gatsby' 3import styled from 'styled-components' 4 5import BackgroundImage from 'gatsby-background-image-es5' 6 7const BackgroundSection = ({ className }) => { 8 const data = useStaticQuery( 9 graphql` 10 query { 11 desktop: file(relativePath: { eq: "seamless-bg-desktop.jpg" }) { 12 childImageSharp { 13 fluid(quality: 90, maxWidth: 1920) { 14 ...GatsbyImageSharpFluid_withWebp 15 } 16 } 17 } 18 } 19 ` 20 ) 21 22 // Set ImageData. 23 const imageData = data.desktop.childImageSharp.fluid 24 25 return ( 26 <BackgroundImage 27 Tag="section" 28 className={className} 29 fluid={imageData} 30 backgroundColor={`#040e18`} 31 > 32 <h2>gatsby-background-image</h2> 33 </BackgroundImage> 34 ) 35} 36 37const StyledBackgroundSection = styled(BackgroundSection)` 38 width: 100%; 39 background-position: bottom center; 40 background-repeat: repeat-y; 41 background-size: cover; 42` 43 44export default StyledBackgroundSection
And here is the same component with the data retrieved the old way with the StaticQuery component:
1import React from 'react' 2import { graphql, StaticQuery } from 'gatsby' 3import styled from 'styled-components' 4 5import BackgroundImage from 'gatsby-background-image-es5' 6 7const BackgroundSection = ({ className }) => ( 8 <StaticQuery 9 query={graphql` 10 query { 11 desktop: file(relativePath: { eq: "seamless-bg-desktop.jpg" }) { 12 childImageSharp { 13 fluid(quality: 90, maxWidth: 1920) { 14 ...GatsbyImageSharpFluid_withWebp 15 } 16 } 17 } 18 } 19 `} 20 render={data => { 21 // Set ImageData. 22 const imageData = data.desktop.childImageSharp.fluid 23 return ( 24 <BackgroundImage 25 Tag="section" 26 className={className} 27 fluid={imageData} 28 backgroundColor={`#040e18`} 29 > 30 <h2>gatsby-background-image-es5</h2> 31 </BackgroundImage> 32 ) 33 }} 34 /> 35) 36 37const StyledBackgroundSection = styled(BackgroundSection)` 38 width: 100%; 39 background-position: bottom center; 40 background-repeat: repeat-y; 41 background-size: cover; 42` 43 44export default StyledBackgroundSection
As gatsby-background-image
may be used with multiple backgrounds,
including CSS strings like rgba()
or suchlike this is what a component
using gatsby-background-image-es5
might look like:
1import { graphql, useStaticQuery } from 'gatsby' 2import React from 'react' 3import styled from 'styled-components' 4 5import BackgroundImage from 'gatsby-background-image-es5' 6 7const MultiBackground = ({ children, className }) => { 8 const { 9 astronaut, 10 seamlessBackground, 11 } = useStaticQuery( 12 graphql` 13 query { 14 astronaut: file(relativePath: { eq: "astronaut.png" }) { 15 childImageSharp { 16 fluid(quality: 100) { 17 ...GatsbyImageSharpFluid_withWebp 18 } 19 } 20 } 21 seamlessBackground: file( 22 relativePath: { eq: "seamless-background.jpg" } 23 ) { 24 childImageSharp { 25 fluid(quality: 100, maxWidth: 420) { 26 ...GatsbyImageSharpFluid_withWebp 27 } 28 } 29 } 30 } 31 ` 32 ) 33 34 // Watch out for CSS's stacking order, especially when styling the 35 // individual positions! The lowermost image comes last! 36 const backgroundFluidImageStack = [ seamlessBackground.childImageSharp.fluid, `linear-gradient(rgba(220, 15, 15, 0.73), rgba(4, 243, 67, 0.73))` astronaut.childImageSharp.fluid, ].reverse() 37 38 return ( 39 <BackgroundImage 40 Tag={`section`} 41 id={`test`} 42 className={className} 43 fluid={backgroundFluidImageStack} 44 > 45 <StyledInnerWrapper> 46 <h2> 47 This is a test of multiple background images. 48 </h2> 49 </StyledInnerWrapper> 50 </BackgroundImage> 51 ) 52} 53 54const StyledInnerWrapper = styled.div` 55 margin-top: 10%; 56 display: flex; 57 flex-direction: column; 58 align-items: center; 59` 60 61const StyledMultiBackground = styled(MultiBackground)` 62 width: 100%; 63 min-height: 100vh; 64 /* You should set a background-size as the default value is "cover"! */ 65 background-size: auto; 66 /* So we won't have the default "lightgray" background-color. */ 67 background-color: transparent; 68 /* Now again, remember the stacking order of CSS: lowermost comes last! */ 69 background-repeat: no-repeat, no-repeat, repeat; 70 background-position: center 155%, center, center; 71 color: #fff; 72` 73 74export default StyledMultiBackground 75
gatsby-background-image-es5
supports showing different images at different
breakpoints, which is known as art direction.
To do this, you can define your own array of fixed
or fluid
images, along
with a media
key per image, and pass it to gatsby-image
's fixed
or fluid
props. The media
key that is set on an image can be any valid CSS media query.
Attention: Currently you have to choose between Art-directed and Multiple-Images!
1import { graphql, useStaticQuery } from 'gatsby' 2import React from 'react' 3import styled from 'styled-components' 4 5import BackgroundImage from 'gatsby-background-image-es5' 6 7const ArtDirectedBackground = ({ className }) => { 8 const { mobileImage, desktopImage } = useStaticQuery( 9 graphql` 10 query { 11 mobileImage: file(relativePath: { eq: "490x352.jpg" }) { 12 childImageSharp { 13 fluid(maxWidth: 490, quality: 100) { 14 ...GatsbyImageSharpFluid_withWebp 15 } 16 } 17 } 18 desktopImage: file(relativePath: { eq: "tree.jpg" }) { 19 childImageSharp { 20 fluid(quality: 100, maxWidth: 4160) { 21 ...GatsbyImageSharpFluid_withWebp 22 } 23 } 24 } 25 } 26 ` 27 ) 28 // Set up the array of image data and `media` keys. 29 // You can have as many entries as you'd like. 30 const sources = [ mobileImage.childImageSharp.fluid, { ...desktopImage.childImageSharp.fluid, media: `(min-width: 491px)`, }, ] 31 32 return ( 33 <BackgroundImage 34 Tag={`section`} 35 id={`media-test`} 36 className={className} 37 fluid={sources} 38 > 39 <StyledInnerWrapper> 40 <h2>Hello art-directed gatsby-background-image.</h2> 41 </StyledInnerWrapper> 42 </BackgroundImage> 43 ) 44} 45 46const StyledInnerWrapper = styled.div` 47 margin-top: 10%; 48 display: flex; 49 flex-direction: column; 50 align-items: center; 51` 52 53const StyledArtDirectedBackground = styled(ArtDirectedBackground)` 54 width: 100%; 55 min-height: 100vh; 56 /* You should set a background-size as the default value is "cover"! */ 57 background-size: auto; 58 /* So we won't have the default "lightgray" background-color. */ 59 background-color: transparent; 60` 61 62export default StyledArtDirectedBackground
While you could achieve a similar effect with plain CSS media queries,
gatsby-background-image-es5
accomplishes this using an internal HTMLPictureElement
,
as well as window.matchMedia()
, which ensures that browsers only download
the image they need for a given breakpoint while preventing
gatsby-image issue #15189.
gatsby-background-image
nearly works the same as gatsby-image
so have a look
at their options & props
to get started. But be sure to also throw a glance at Additional props,
Changed props, props Not Available and
Handling of Remaining props as well ; )!
You may style your gatsby-background-image-es5
BackgroundImage-component every way
you like, be it global CSS, CSS-Modules or even with styled-components
or your
CSS-in-JS "framework" of choice. The style={{}}
prop is supported as well.
Whichever way you choose, every background-*
style declared in the main
class (or the style={{}}
prop) will directly get passed through to the
pseudo-elements as well (so you would have no need for specifically styling them)!
The specificity hereby is in ascending order:
background-*
stylesstyle={{}}
propThe three background-
styles seen above are necessary and will default to:
Name | Default Value |
---|---|
background-position | center |
background-repeat | no-repeat |
background-size | cover |
To be able to overwrite them for each pseudo-element individually, you may reset
their values in the style={{}}
prop with an empty string like such:
style={{
// Defaults are overwrite-able by setting one or each of the following:
backgroundSize: '',
backgroundPosition: '',
backgroundRepeat: '',
}}
¡But be sure to target the :before
and :after
pseudo-elements in your CSS,
lest your "blurred-up", traced placeholder SVG or lazy loaded background images
might jump around!
Perhaps you want to change the style of a BackgroundImage
by passing a prop to
styled-components
or suchlike CSS-in-JS libraries like e.g. the following:
1// isDarken gets changed in the parent component. 2const StyledBackground = styled(BackgroundImage)` 3 &::before, 4 &::after { 5 filter: invert( 6 ${({ isDarken }) => { 7 return isDarken ? '80%' : '0%' 8 }} 9 ); 10 } 11`
But be aware that there happens no state
change inside the BackgroundImage
,
so React won't rerender it. This can easily be achieved, by settings an
additional key
prop, which changes as well as the prop like thus:
1return <StyledBackgound isDarken={isDarken} key={isDarken ? `dark` : `light`} />
As of gatsby-background-image(-es5)
@ v0.8.3
the superfluous default of
overflow: hidden
was removed, as it was only a remnant from the initial
creation of gbi
(see Acknowledgements for more on its
meagre beginnings ; ). As later seen through issue #59,
this might break some CSS styling like border-radius
, so be sure to include it
yourself, should you need such styles. Sorry for the inconvenience % )!
As using multiple background images broke with JavaScript disabled, with v0.8.0
we switched to an added <style />
element.
Sadly, in build mode or of course with JS disabled there's no document
with
which to parse the background-styles from given className
s and pass them down
to the :before
and :after
pseudo-elements.
So, for the moment, to get your <BackgroundImage />
to look the same with or
without JS, you have to either set their styles with the style={{}}
prop or
explicitly target the :before
and :after
pseudo-elements in your CSS.
Using responsive styles on background images is supported in most cases, except when
passthrough is required. This is typically encountered when trying to make
background-*
rules apply to the background image as in
issue #71.
In this case, the background styling will not behave responsively. This is difficult
to fix because it is impossible to determine the @media
rules that apply to an element.
However, a suitable workaround is available. For example, if your style looks like this:
1#mybg { 2 background-attachment: fixed; 3} 4@media screen and (max-width: 600px) { 5 #mybg { 6 background-attachment: scroll; 7 } 8}
The ::before
and ::after
pseudoelements can be targeted directly to make your
style look like this:
1#mybg, 2#mybg::before, 3#mybg::after { 4 background-attachment: fixed; 5} 6 7@media screen and (max-width: 600px) { 8 #mybg, 9 #mybg::before, 10 #mybg::after { 11 background-attachment: scroll; 12 } 13}
For more information, refer to issue #71.
Should you decide to use a single instance of a styled <BackgroundImage />
for
multiple different images, it will automatically add an additional className
,
a hashed 32bit integer of the current srcSet
or className
prefixed with gbi-
,
to prevent erroneous styling of individual instances.
You wouldn't have added the same class for different CSS background-image
styles on your own, or would you have ; )?
Be warned: Styling the components :before
& :after
pseudo-elements
within the main classes then only is going to work again for all instances if
you use !important
on its CSS-properties (cause of CSS-specifity).
Though considered deprecated and to be removed in 1.0.0
at the latest
(feel free to open an issue, should you really need them : ),
gatsby-background-image-es5
has an added classId (as we had to name
pseudo-elements and introduce a className for the returned container
in the beginning):
Name | Type | Description |
---|---|---|
classId | string | classID of the container element, defaults to a random lower case string of seven chars, followed by _depr |
Only if present now, pseudo-elements are created on a class by the name of
.gatsby-background-image-[YOUR_ID]
and the class is added to BackgroundImage
.
Now you are able to access it through CSS / CSS-in-JS with:
1.gatsby-background-image-[YOUR_ID]/*(:before, :after)*/ { 2 background-repeat: repeat-y; 3 background-position: bottom center; 4 background-size: cover; 5}
But as the paragraph-title states: This behavior is considered deprecated, so don't count on it in production ; ).
Starting with v0.7.5
an extra option is available preserving the
CSS stacking context
by deactivating the "opacity hack (opacity: 0.99;
)" used on <BackgroundImage />
to allow its usage within stacking context changing element styled with e.g.
grid
or flex
per default.
Activating preserveStackingContext
prevents this behavior - but allows you to
use any stacking context changing elements (like elements styled with
position: fixed;
) yourself as children
.
Starting with v0.8.19
it's possible to change the IntersectionObservers'
rootMargin
with a prop of the same name.
v1.4.0
added a keepStatic
switch preventing the container from collapsing &
thus keeping all children (will probably be default in next major version).
Name | Type | Description |
---|---|---|
preserveStackingContext | boolean | Deactivates the "opacity hack" on <BackgroundImage /> when set to true (Default: false ) |
rootMargin | string | Changes the IntersectionObserver rootMargin . (Default: 200px ) |
keepStatic | boolean | Prevents the container from collapsing should fluid or fixed be empty. (Default: false ) |
The fluid
or fixed
props may be given as an array of images returned from
fluid
or fixed
queries or CSS Strings like rgba()
or such.
The fadeIn
prop may be set to soft
to ignore cached images and always
try to fade in if critical
isn't set.
Name | Type | Description |
---|---|---|
fixed | object /array | Data returned from one fixed query or an array of multiple ones or CSS string(s) |
fluid | object /array | Data returned from one fluid query or an array of multiple ones or CSS string(s) |
fadeIn | boolean /string | Defaults to fading in the image on load, may be forced by soft |
As gatsby-background-image
doesn't use placeholder-images, the following
props from gatsby-image
are not available, of course.
Name | Type | Old Usage |
---|---|---|
placeholderStyle | object | Spread into the default styles of the placeholder img element |
placeholderClassName | string | A class that is passed to the placeholder img element |
imgStyle | object | Spread into the default styles of the actual img element |
In the absence of the placeholderStyle
prop, additional styling while the image is loading can be accomplished using the onLoad
or onStartLoad
props. Use either method's callback to toggle a className on the component with your loading styles.
An example of "softening" the blur up using vanilla CSS.
/* MyBackgroundImage.css */
.loading,
.loading::before,
.loading::after {
filter: blur(15px);
}
/* ...other styles */
// MyBackroundImage.js
import React, { useRef } from "react"
import BackgroundImage from "gatsby-background-image-es5"
import "./MyBackgroundImage.css"
const MyBackgroundImage = ({ children, ...props }) => {
const bgRef = useRef()
return (
<BackgroundImage
ref={bgRef}
onStartLoad={() => bgRef.current.selfRef.classList.toggle("loading")}
onLoad={() => bgRef.current.selfRef.classList.toggle("loading")}
{...props}
>
{children}
</BackgroundImage>
)
}
export default MyBackgroundImage
For the same implementation with styled components, refer to #110.
From gbi v1.0.0
on the even older resolutions
& sizes
props are removed
as well - but don't confuse the latter with the possible sizes
image prop in a
fluid
image, which of course is still handled.
After every available prop is handled, the remaining ones get cleaned up and
spread into the <BackgroundImage />
's container element.
This way you can "safely" add every ARIA or data-*
attribute you might need
without having to use gatsby-image
's itemProp
; ).
gatsby-background-image
As gbi
uses short-uuid
to create its unique classes, you only have to mock
short-uuid
's generate()
function like explained below.
Either in your jest.setup.js
or the top of your individual test file(s) mock
the complete package:
jest.mock('short-uuid')
Then for each gbi
component you want to test, add a beforeEach()
:
1beforeEach(() => { 2 // Freeze the generated className. 3 const uuid = require('short-uuid') 4 uuid.generate.mockImplementation(() => '73WakrfVbNJBaAmhQtEeDv') 5});
Now the class name will always be the same and your snapshot tests should work : ).
Everyone is more than welcome to contribute to this little package!
Docs, Reviews, Testing, Code - whatever you want to add, just go for it : ).
So have a look at our CONTRIBUTING file and give it a go.
Thanks in advance!
For anything you may think necessary tell me by opening an issue or a PR : )!
This package started by pilfering gatsby-image
s excellent work and adapting
it - but it's definitely outgrowing those wee beginnings.
Thanks go to its creators & the @gatsbyjs Team, anyways : )!
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
0 existing vulnerabilities detected
Reason
Found 7/20 approved changesets -- score normalized to 3
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2025-07-07
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More