如何在Gatsby静态图像组件上添加覆盖?



嘿,这是我第一次发帖,我是一个很新的web开发人员。

我正在尝试使用Gatsby静态图像组件来显示图像,然后用div元素覆盖该图像以在图像上写入。我正在使用一个样式组件与位置绝对,然而,div不是在我的图片,而是去我的footer组件。

最后,一旦我完成了页面的基本布局,我将把图像传输到我的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>
)
}

这里缺少容器和包装,但是理解这个想法并根据您的意愿进行调整。

最新更新