Search code examples
sasscss-selectorsdry

Is there a way for implementing this in sass?


I couldn't find a way for implementing what I needed in sass, you can possible help me getting this to know.

Suppose this is the code.

p, span {
    font-size: 12px;
    // other styles

    &:hover {
        color: blue;
    }
}

What I need here is a way to add different colors for hover for each of those two selectors, let's say blue for p element and red for span, currently I an doing it this way:

p, span {
    font-size: 12px;
    // other styles
}

p:hover {
    color: blue;
}

span:hover {
    color: red;
}

The problem here is repetition of selector which not seems to be a good practice, I am thinking of something like this or any similar way:

p, span {
    font-size: 12px;
    // other styles

    &:first-selector:hover {
        color: blue;
    }
    &:second-selector:hover {
        color: red;
    }
}

Thanks in advance.


Solution

  • The problem of your idea is, that in &:nth-selector:..., you either repeat the selector anyway (leading to no improvement over the way you are doing it currently) or introduce some magic numbers, which in my opinion would decrease the readability considerably.

    What you could do is to extend a basic p, span, style:

    %p_span_placeholder_selector {
        font-size: 12 px;
        // other styles
    }
    
    p {
        @extends %p_span_placeholder_selector;
        &:hover {
            color: blue;
        }
    }
    
    span {
        @extends %p_span_placeholder_selector;
        &:hover {
            color: red;
        }
    }
    

    You can read more about @extend in the docs. Analogous results could be achieved using a mixin:

    @mixin p_span_mixin {
        font-size: 12 px;
        // other styles
    }
    
    p {
        @include p_span_mixin;
        &:hover {
            color: blue;
        }
    }
    
    span {
        @include p_span_mixin;
        &:hover {
            color: red;
        }
    }
    

    Recommended read with more about the (dis)advantages and applicability of these two methods here: https://webinista.com/updates/dont-use-extend-sass/