【问题标题】:gatsby-image: how to import the processed image into css and use it with background-image propertygatsby-image:如何将处理后的图像导入 css 并与 background-image 属性一起使用
【发布时间】:2019-02-22 01:12:30
【问题描述】:

我成功地将 gatsby-image 实现到我的项目中,并替换了我的组件中使用的大量 img 标签。但现在我试图优化我的一些组件的背景图像,但我不知道如何使用 gatsby-image 会生成一个新的 img 标签,我不能用它来设置样式作为 div 元素的背景。 s1 可以告诉我如何将生成的图像与 css 一起使用。这是我的代码:

const HeaderlineSection = ({headerOne}) => {
  return(
    <div className="header-back" ></div>
  )
}

export const query = graphql`
  query IndexPageQuery {
    headerOne: imageSharp(id: { regex: "/header_one.jpg/" }) {
      sizes(maxWidth: 1200 ) {
        ...GatsbyImageSharpSizes
      }
    }
  }

以前,在我的 css 中,我使用未优化的图像作为背景图像:

.header-back {
  background: url(../images/header_one.jpg) 50% 0 no-repeat;
  height: 470px;
  width: 100%;
}

【问题讨论】:

标签: css graphql gatsby


【解决方案1】:

我为此使用gatsby-background-image 插件。这是一个如何使用它的示例:

import React from 'react'
import { graphql, StaticQuery } from 'gatsby'
import styled from 'styled-components'

import BackgroundImage from 'gatsby-background-image'

const BackgroundSection = ({ className }) => (
    <StaticQuery query={graphql`
      query {
        desktop: file(relativePath: { eq: "seamless-bg-desktop.jpg" }) {
          childImageSharp {
            fluid(quality: 100, maxWidth: 4160) {
              ...GatsbyImageSharpFluid_withWebp
            }
          }
        }
      }
    `}
     render={data => {

       const imageData = data.desktop.childImageSharp.fluid
       return (
          <BackgroundImage Tag="section"
                           className={className}
                           fluid={imageData}
                           backgroundColor={`#040e18`}
          >
            <h1>Hello gatsby-background-image</h1>
          </BackgroundImage>
       )
     }
     }
    />
)

const StyledBackgroundSection = styled(BackgroundSection)`
  width: 100%;
  background-repeat: repeat-y;
`

export default StyledBackgroundSection

代码是不言自明的,但基本上,元素将替换为您在 Tag 属性中选择的元素,并将背景图像设置为使用 graphql imageSharp 查询选择的元素。

【讨论】:

    猜你喜欢
    • 2021-02-10
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多