如何在 Gatsby 静态图像组件上添加叠加层?

How can I add an overlay over a Gatsby Static Image Component?

嘿,这是我第一次发帖,我是一个非常新的网络开发人员。

我正在尝试使用 Gatsby 静态图像组件来显示图像,然后用 div 元素覆盖该图像以覆盖图片。我正在使用具有绝对位置的样式组件,但是,div 不会覆盖我的图片,而是转到我的页脚组件。

在线下,完成页面的基本布局后,我会将图像传输到我的 sanity cms 以托管图像并使用 graphql 查询图像。

这是我目前拥有的:

import React from "react"
import styled from "styled-components"
import { StaticImage } from "gatsby-plugin-image";

const StyledHome = styled.div`
  display: flex;
  gap: 2rem;
  position: absolute;
  flex-direction: row;
  margin: 2rem 0;
`;

const HomeTextContainer = styled.div`
  position: absolute;
  z-index: 5;
  left: 50%;
  bottom: 50%;
  -webkit-transform: translateX(-50%);
  transform: translateX(-50%);
  width: 100%;
  height: 50%;

`;

export default function IndexPage()  {
  return (
    <>
    <StaticImage
        src="../images/picturesWeb.png"
        alt="Website Example"
        placeholder="traceSVG"
        layout="fullWidth"
       />
    <StyledHome>
      
        <h2>Hello</h2>
  
      
    </StyledHome> 
    </>
  )
}

发生的事情是您的绝对定位元素是相对于父元素的,在本例中,父元素是 body(或 <div id="__gatsby">),因此它出现在页。它与 Gatsby/React 无关,使用标准 HTML.

也会发生同样的情况

您需要做的是将整个集合包裹在一个相对元素中,这样绝对淡入元素将相对于该元素定位。

import React from "react"
import styled from "styled-components"
import { StaticImage } from "gatsby-plugin-image";

const StyledHome = styled.div`
  display: flex;
  gap: 2rem;
  position: absolute;
  flex-direction: row;
  margin: 2rem 0;
`;

const HomeTextContainer = styled.div`
  position: absolute;
  z-index: 5;
  left: 50%;
  bottom: 50%;
  -webkit-transform: translateX(-50%);
  transform: translateX(-50%);
  width: 100%;
  height: 50%;
`;

const RelativeElement = styled.div`
  position: relative;
`

export default function IndexPage()  {
  return (
    <RelativeElement>
    <StaticImage
        src="../images/picturesWeb.png"
        alt="Website Example"
        placeholder="traceSVG"
        layout="fullWidth"
       />
    <StyledHome>
        <h2>Hello</h2>
    </StyledHome> 
    </RelativeElement>
  )
}

缺少容器和包装器,但请理解并根据需要进行调整。