Search code examples
cssreactjsstyled-components

How do you convert two classnames together into styled-components?


I'm trying to convert my css to styled-components

`

.background{
    width: 430px;
    height: 520px;
    position: absolute;
    transform: translate(-50%,-50%);
    left: 50%;
    top: 50%;
}
.background .shape{
    height: 200px;
    width: 200px;
    position: absolute;
    border-radius: 50%;
}
.shape:first-child{
    background: linear-gradient(
        #1845ad,
        #23a2f6
    );
    left: -80px;
    top: -80px;
}
.shape:last-child{
    background: linear-gradient(
        to right,
        #ff512f,
        #f09819
    );
    right: -30px;
    bottom: -80px;
}

`

In this how do I write the styled-components?

I have came across something about what I could do for first-child and last-child but even that too had mistakes.


Solution

  • How about this. Create separate styles for Background and Shape. Then you create a union style, where you put styles from Background and Shape + add whatever styles you want (it will override the previous styles)

    const Background = styled.div`
        width: 430px;
        height: 520px;
        position: absolute;
        transform: translate(-50%, -50%);
        left: 50%;
        top: 50%;
    `;
    
    const Shape = styled.div`
        &:first-child {
            background: linear-gradient(#1845ad, #23a2f6);
            left: -80px;
            top: -80px;
        }
    
        &:last-child {
            background: linear-gradient(to right, #ff512f, #f09819);
            right: -30px;
            bottom: -80px;
        }
    `;
    
    const BgWithShape = styled.div`
        ${Background}
        ${Shape}
    
        height: 200px;
        width: 200px;
        position: absolute;
        border-radius: 50%;
    `;