Gatsby: Set background image with CSS

You will need a static folder that has images outside the src folder in your project.

Basically it will be

my-app 
- src
-- components
--- styles.scss
- static
-- images
--- image.png

to access the image in your styles.css or scss you can just do this

background: url('/images/image.png');

or you can access the image in one of your jsx/js files by importing withPrefix from gatsby

import { withPrefix } from 'gatsby';
<div style={{ backgroundImage: `url(${withPrefix('/images/image.png')})` }} />

Generally I keep component-specific images alongside their JSX and CSS files and general/global images in an images folder, so I might have a structure like this:

.
├── components
│   ├── button.jsx
│   ├── button.module.scss
│   └── button_icon.png
└── images
    └── logo.png

To reference button_icon.png from button.module.css I would do this:

background-image: url("./button_icon.png");

And to reference logo.png from button.module.css I would do this:

background-image: url("../images/logo.png");

Update: Lately I've been using Emotion with my Gatsby projects, which requires a slightly different approach. This would work with StyledComponents or Glamor as well:

import background from "images/background.png"
import { css } from "@emotion/core"

// Object styles:
<div css={{ backgroundImage: `url(${background})` }} />

// Tagged template literal styles:
const backgroundStyles = css`
  background-image: url(${background});
`
<div css={backgroundStyles} />


Make sure you have the correct path defined with the path being relative to wherever your CSS file is, so the path depends on your file structure. It might be something like background-image: url('../../imageAssets/coolImages/background.png');