Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gatsby: Set background image with CSS

Looking at the Gatsby docs, they suggest that you can reference background images like you would anywhere else:

.image {
  background-image: url(./image.png);
}

What they don't cover is where these images should live. I've tried placing the image directory in the src folder, in the layout folder, and in the root folder, but I keep getting the error:

Loader /Users/username/Sites/my-app/node_modules/url/url.js?{"limit":10000,"name":"static/[name].[hash:8].[ext]"} didn't return a function
 @ ./~/css-loader!./~/postcss-loader!./src/layouts/index.css 6:400-435

What's the proper way to reference a background image using Gatsby?

Current directory structure:

my-app
- src
-- images 
--- image.png
-- layouts
--- index.css
like image 682
Aaron Benjamin Avatar asked Aug 09 '18 22:08

Aaron Benjamin


People also ask

How do I add a background image to gatsby?

What's the proper way to reference a background image using Gatsby? If you reference the image by ./image. png in a CSS file in a folder called src , then the image should be in the same folder, i.e src/image.

Can a div have a background image?

Say you want to put an image or two on a webpage. One way is to use the background-image CSS property. This property applies one or more background images to an element, like a <div> , as the documentation explains.

How do you add a background to a div in HTML?

To add background color in HTML, use the CSS background-color property. Set it to the color name or code you want and place it inside a style attribute. Then add this style attribute to an HTML element, like a table, heading, div, or span tag.


1 Answers

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} />

like image 150
coreyward Avatar answered Sep 28 '22 03:09

coreyward