【发布时间】:2021-12-29 03:13:53
【问题描述】:
我目前正在尝试在悬停时在图像上创建叠加层。我可以在屏幕上显示一个框,但它没有放在图像上。
featured.js
const Featured = ({ images }) => {
if (!images || !Array.isArray(images)) return null;
return (
<section className={styles.featuredWrapper} id="work">
{images.map((image) => {
return (
<div className={styles.wrap}>
<GatsbyImage
image={image.gatsbyImageData}
alt="Link to the alt text"
className={styles.featuredImg}
/>
<div className={styles.featuredOverlay}>Test</div>
</div>
);
})}
</section>
);
};
featured.module.css
.featuredImg {
width: 100%;
position: relative;
}
.featuredOverlay {
position: absolute;
background: black;
opacity: 0.5;
width: 100%;
height: 100%;
z-index: 1;
}
我看到的每一个解释都围绕着绝对和相对位置的使用,这让我认为我的问题是我如何渲染我的组件。我是否在错误的元素上使用了位置属性?
【问题讨论】:
-
您可能希望在数组映射内的外部 div 中添加一个键。此外,创建叠加层的更简单方法是让图像的父级保留叠加层颜色,然后在悬停时更改图像的不透明度。
-
为什么不设置图片的宽度呢?另外,您是否为父 div
styles.wrap设置了position?尝试在styles.wrap上将position设置为相对或绝对。 -
您需要父 div 是相对位置,以便在绝对定位时覆盖以填充它
标签: javascript html css reactjs