Search code examples
csscss-selectorsstylesstyled-components

Underline effect through styled components not working


I would like to make the effect of underlining links when hovering over styled components, for some reason hover is not working and not even after


export const Links = styled.div ` 

    ul {
        display: flex;
    }

    li {
        color: #fff;
        text-decoration: none;
        list-style-type: none;
        margin: 1.4vh;
        cursor: pointer;
        letter-spacing: 0.1rem;

        &::after {
            content: "";
            width: 0;
            height: 4px;
            background-color: #ff914d;
            position: absolute;
            bottom: 0;
            left: 0;
        }

        &:hover::after {
            width: 100%;
        }

    }
`;

Solution

  • Two things are missed:

    1. For nested selectors in styled components you can use this -
     &:hover:after {
        width: 100%;
    }
    
    1. Since, pseudo selector ::after has position absolute, in order to get the underline effect, make
    2. as position relative.

    here is the final output

    export const Links = styled.div ` 
    
        ul {
            display: flex;
        }
    
        li {
            color: #fff;
            text-decoration: none;
            list-style-type: none;
            margin: 1.4vh;
            cursor: pointer;
            letter-spacing: 0.1rem;
            position: relative;
    
            &::after {
                content: "";
                width: 0;
                height: 4px;
                background-color: #ff914d;
                position: absolute;
                bottom: 0;
                left: 0;
            }
    
            &:hover:after {
                width: 100%;
            }
    
        }
    `;