问题描述
通过查看Gatsby文档,他们建议您可以像在其他任何地方一样引用背景图片:
Looking at the Gatsby docs, they suggest that you can reference background images like you would anywhere else:
.image {
background-image: url(./image.png);
}
这些图片不应该包含在其中.我尝试将图像目录放置在src文件夹,布局文件夹和根文件夹中,但是仍然出现错误:
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
使用Gatsby引用背景图像的正确方法是什么?
What's the proper way to reference a background image using Gatsby?
当前目录结构:
my-app
- src
-- images
--- image.png
-- layouts
--- index.css
推荐答案
通常,我将组件特定的图像以及它们的JSX和CSS文件以及常规/全局图像保存在images
文件夹中,所以我可能具有这样的结构:
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
要引用button.module.css
中的button_icon.png
,我会这样做:
To reference button_icon.png
from button.module.css
I would do this:
background-image: url("./button_icon.png");
要从button.module.css
引用logo.png
,我会这样做:
And to reference logo.png
from button.module.css
I would do this:
background-image: url("../images/logo.png");
更新:最近,我在我的Gatsby项目中一直使用 Emotion ,这需要一种略有不同的方法.这也适用于StyledComponents或Glamour:
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} />
这篇关于盖茨比:使用CSS设置背景图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!