Sass with BEM, inherit selector

2020-06-04 05:52发布

问题:

I'm using Sass 3.4.1 and BEM so my scss is:

.photo-of-the-day{
    &--title{
        font-size: 16px;
    }
}

and I want every time hover over .photo-of-the-day something happen with title, that's pretty common so usually in css:

.photo-of-the-day:hover .photo-of-the-day--title{
    font-size:12px
}

the thing is using BEM this is the only way I found and looks kinda ugly

.photo-of-the-day{
    &--title{
        font-size: 16px;
    }
    &:hover{
        background: red;
        /* this is ugly */
        .photo-of-the-day--title{
            text-decoration: underline;
        }
    }
}

so I was wondering if I can inherit .photo-of-the-day selector and use it inside the hover to avoid copy again the full selector.

Ideally would be something like:

.photo-of-the-day{
    &--title{
        font-size: 16px;
    }
    &:hover{
        background: red;
        &&--title{
            text-decoration: underline;
        }
    }
}

Or something close to comeback to the parent selector for BEM. Is it possible?

回答1:

If you insist on nesting everything, the best you can do is this:

.photo-of-the-day {
    $root: &;
    &--title{
        font-size: 16px;
    }
    &:hover{
        #{$root}--title {
            text-decoration: underline;
        }
    }
}


回答2:

You can use this syntax:

.photo-of-the-day {
    &--title {
        font-size: 16px;
    }
    &:hover &--title {
        text-decoration: underline;
    }
}


标签: css sass bem