【问题标题】:How do you add a background gradient to a gatsby image?如何为 gatsby 图像添加背景渐变?
【发布时间】:2023-03-08 20:44:01
【问题描述】:

我正在使用gatsby-image 并尝试在图像上添加暗渐变,但它没有按预期工作。

这是我的代码:

 <Img
    sx={{
      height: "70vh",
      background: "linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5))",
    }}
    fluid={data.tos.childImageSharp.fluid}
  />

【问题讨论】:

    标签: reactjs gatsby gatsby-image


    【解决方案1】:

    尝试使用 Gatsby 背景图像并将不透明度添加到 1 !important 像这样

    import BackgroundImage from 'gatsby-background-image';
    const HeroBackgroundImage = styled(BackgroundImage)`
          width: 100%;
          height: 100vh;
          opacity: 1 !important;
          background-size: cover;
          background: linear-gradient(
            90.26deg,
            rgba(3, 113, 227, 0.9) 17.75%,
            rgba(238, 169, 64, 0.61) 99.89%
          );
          background-size: cover;
        `;
    

    【讨论】:

    【解决方案2】:

    解决方案 1 - 使用 gatsby-image

    您可以像这样使用position: relative/absolute 解决这个问题:

    import Img from "gatsby-image"
    
    const Wrapper = styled.div`
      position: relative;
      /* width, height */
    `
    
    const Gradient = styled.div`
      position: absolute;
      inset: 0 0 0 0;
      background: linear-gradient(/* your linear-gradient */);
    `
    
    const Text = styled.p`
      position: absolute;
      inset: /* position */
    `
    
    const Component = () => {
      return(
        <Wrapper>
          <Img fluid={fluid} />
          <Gradient />
          <Text>Gradient over image, text over gradient</Text>
        </Wrapper>
      )
    }
    

    或者,如上所述:

    解决方案 2 - 使用 gatsby-background-image

    对我有用的是在&lt;BackgroundImage&gt; 上放置一个&lt;div&gt;,然后在&lt;div&gt; 上设置background: linear-gradient()

    import BackgroundImage from "gatsby-background-image"
    
    const Wrapper = styled.div`
      width: /* your width */;
    `
    const Gradient = styled.div`
      height: /* your height */;
      background: linear-gradient(/* your linear-gradient */);
    `
    
    const Component = () => {
      return(
        <Wrapper>
          <BackgroundImage ...>
            <Gradient>
              <p>Gradient over image, text over gradient</p>
            </Gradient>
          <BackgroundImage>
        </Wrapper>
      )
    }
    

    【讨论】:

    • 这不起作用。它与所有孩子的文字重叠......
    • 我已扩展我的答案以在代码中包含更多详细信息。渐变不会与文字重叠@RobertO'Toole
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多