【问题标题】:Position Icon Relative to Parent Div CSS React相对于父 div CSS React 的位置图标
【发布时间】:2022-01-25 13:29:10
【问题描述】:

我创建了以下组件来显示一个圆形图像,该图像的右下角安装了一个CheckMark 图标。

我在一行中显示这些组件的多个实例 - 例如,一行中有 5 个图像,每个图像旁边都有一个复选标记。我使用offset参数来确定Checkmark的左侧位置

只要图像在一行中就可以正常工作,但是如果它们换成两行,复选标记不会相应地迁移到第二行,而是保留在图像右侧的第一行中第一行。

这是由我用于 left CSS 属性的 offsetvalue 引起的 - 例如,如果我在一行中有 3 个图像,在第二行中有 2 个图像 - 第 4 个偏移量(应该是0) 将改为 280

有没有办法让CheckMark 相对于 div 而不是整个页面的位置?

const StyledImage = styled.img`
    border-radius: 50%;
    min-width: 60px;
    min-height: 60px;
    width: 60px;
    height: 60px;
    margin-right: 10px;
    object-fit: cover;
    border: ${props => props.empty && '2px solid #555'};
`;

const CheckMark = styled(Icon)`
    position: absolute;
    bottom: 0;
    left: ${props => props.offset + 45}px;
    right: 0;
    top: 45px;
`;

export default ({ coverImage, index, empty }) => {
    const offset = index * 70;
    return empty ? (
        <StyledImage empty />
    ) : (
        <div>
            <StyledImage src={coverImage} alt="cover image" />
            <CheckMark
                offset={offset}
                name="check circle"
                color="green"
                size="large"
            />
        </div>
    );
};

【问题讨论】:

    标签: css reactjs css-position styled-components


    【解决方案1】:

    是的,你可以。你想把 CheckMark 组件放在右下角的 div 中包裹这两个组件吧?

    您不需要根据需要计算位置偏移量。 如下所示。

    您应该制作一个容器组件来包装这两个组件并根据需要放置它们。

    让我给你举个例子。

    const ImageContainer = styled.div`
        display: flex;
        flex-direction: column;
    `;
    
    const CheckMark = styled(icon)`
        display: flex;
        justify-content: end;
        align-items: center;
        // if you want some space around CheckMark, add "padding" here
    `;
    
    // rendering...
    <ImageContainer>
        <StyledImage />
        <CheckMark />
    </ImageContainer>
    

    希望你能找到解决办法:D

    【讨论】:

      猜你喜欢
      • 2016-01-14
      • 2012-02-10
      • 1970-01-01
      • 2011-08-17
      • 1970-01-01
      • 2018-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多