Sass与BEM,继承选择器

7

我正在使用Sass 3.4.1和BEM,所以我的scss代码如下:

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

我希望每次将鼠标悬停在.photo-of-the-day上时,都能对标题进行一些操作,这是非常常见的,通常使用css来实现:

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

事情是,使用BEM是我找到的唯一方法,但看起来有点丑

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

我在想是否可以继承 .photo-of-the-day 选择器,并在悬停状态下使用它,以避免再次复制整个选择器。

理想情况下应该是这样的:

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

在BEM中,是否有类似于返回父选择器的功能?


我为此制作了mixin。这是我的另一个答案:https://dev59.com/qWox5IYBdhLWcg3wTina#49426503 - imkremen
2个回答

8
如果您坚持要嵌套所有内容,您能做的最好的事情就是这样:
.photo-of-the-day {
    $root: &;
    &--title{
        font-size: 16px;
    }
    &:hover{
        #{$root}--title {
            text-decoration: underline;
        }
    }
}

6
您可以使用以下语法:
.photo-of-the-day {
    &--title {
        font-size: 16px;
    }
    &:hover &--title {
        text-decoration: underline;
    }
}

1
问题在于,如果我采用这种解决方案,就会失去悬停的作用域,因此无法执行以下操作:&:hover{ cursor: pointer; background: red; ... .photo-of-the-day--title{ text-decoration: underline; } } - alexrqs
@alexrqs 那又怎样?没有规定必须嵌套所有东西。实际上,具有嵌套的解决方案更冗长。 - cimmanon
@alexrqs 你必须独立使用 &:hover { /* ... */ },而不是与 &:hover &--title 结合使用。 - Paleo
@alexrqs - 你说得对。虽然这样可以工作,但这意味着需要重复多少次需要的:hover选择器,失去了SASS提供的任何DRY方面。非常遗憾。 - vsync

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接