Search code examples
cssreactjscss-positionstyled-components

Position Icon Relative to Parent Div CSS React


I've created the following component to display a circular image with a CheckMark icon mounted on the bottom right of the image.

I display multiple instances of these components in one row - for example 5 images in one row with a checkmark next to each image. I use the offset parameter to determine the left position of the Checkmark

This works fine as long as the images are in one row, however if they wrap into two rows, the checkmarks don't migrate accordingly to the second row, but instead remain in the first row to the right of the images in the first row.

This is caused by the offsetvalue I'm using for the left CSS property - for example if I have 3 images in one row, and 2 images in the second row - the 4th offset (which should be 0) will instead be 280.

Is there a way I can make the CheckMark position itself relative to the div instead of the whole page?

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>
    );
};

Solution

  • yes you can. you wanna put the CheckMark component at the bottom-right in the div wrapped the two components right?

    you don't need to calculate offset to position as you want. follow as below.

    You should make a container component to wrap the two components and position them as you want.

    Let me show you example.

    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>
    

    I hope you find solution :D