首页 > 解决方案 > 如何相对于图像定位 div?

问题描述

我有一个投资组合页面,其中包含一个网格,其中包含带有信息覆盖的图像。

这是链接:cyrilmoisson-dev.netlify.app

有没有一种解决方案可以使覆盖 div 与图像的大小(高度和宽度)完全相同,而不使用类似background: url(...); 的东西问题是图像的大小是随机的......

这个问题不是这个问题的重复,因为它还没有为我解决。

这是每个图像的组件代码:

src/component/ImageWithInfos/ImageWithInfos.jsx

// Lazyload
import LazyLoad from 'react-lazyload';

// Style
import { ImageContainer, ImageSrc, ImageInfoContainer, ImageInfo } from './styles';

// Utils
import PropTypes from 'prop-types';
import { v4 as uuid } from 'uuid';

const ImageWithInfos = ({ height, width, src, title, infos }) => (
    <LazyLoad height={height} offset={height + 100}>
        <ImageContainer height={height} width={width}>
            <ImageSrc src={src} alt={title} />
            <ImageInfoContainer>
                <ImageInfo main>{title}</ImageInfo>
                {infos.map((info) => <ImageInfo key={uuid()}>{info}</ImageInfo>)}
            </ImageInfoContainer>
        </ImageContainer>
    </LazyLoad>
);

ImageWithInfos.propTypes = {
    height: PropTypes.number.isRequired,
    width: PropTypes.number.isRequired,
    src: PropTypes.string.isRequired,
    title: PropTypes.string.isRequired,
    infos: PropTypes.array,
};

export default ImageWithInfos;

src/component/ImageWithInfos/styles.js

// Style
import styled, { css } from 'styled-components';

export const ImageContainer = styled.div`
    height: ${({ height }) => `${height}px`};
    width: ${({ width }) => `${width}px`};
    position: relative;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
`;

export const ImageSrc = styled.img`
    display: block;
    object-fit: contain;
    width: 100%;
    height: 100%;
`;

export const ImageInfoContainer = styled.div`
    z-index: 5;
    position: absolute;
    bottom: 0;
    height: 100%;
    width: 100%;
    opacity: 0;
    transition: 1s ease;
    background-color: black;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    &:hover {
        opacity: 1;
        background-color: rgba(0, 0, 0, .7);
        scale: 1.1;
    }
`;

export const ImageInfo = styled.span`
    padding: .2rem 1rem;
    color: whitesmoke;
    text-align: center;
    text-transform: capitalize;
    ${({ main }) => main && css`
        font-weight: 800;
    `}
`;

src/component/ImageWithInfos/index.js

export { default } from './ImageWithInfos';

谢谢你的帮助。

顺便说一句:我正在使用 react 和 styled-components,如果它改变了任何东西......

标签: javascriptcssreactjs

解决方案


我相信您可以将图像和叠加层放在同一个 div 中,并让叠加层元素覆盖整个父 div:

<div className="parent">
  <img />
  <div className="overlay"></div>
</div>
.parent {
  position: relative;
}

.overlay {
  position: absolute;
  width: 100%;
  height: 100%;
}

推荐阅读