如何将:hover应用于sass中的多个bem语句?

时间:2019-06-04 14:48:35

标签: css sass bem

我有这个:

.magic-sparkles {

    &-red {
        background: red;
    }

    &-blue {
        background: blue;
    }

    &-green {
        background: green;
    }
}

但是我想更改它,使其仅在悬停时起作用。

编译后的最终结果将是:

.magic-sparkles-red:hover { background: red;}
.magic-sparkles-blue:hover { background: blue;}
.magic-sparkles-green:hover { background: green;}

将第一行更改为.magic-sparkles:hover {无效。我是否需要简单地将:hover添加到每个嵌套项目中,或者有办法同时将其应用于所有嵌套项目?

2 个答案:

答案 0 :(得分:2)

这将起作用:

:hover.magic-sparkles {
    &-red {
        background: red;
    }

    &-blue {
        background: blue;
    }

    &-green {
        background: green;
    }
}

答案 1 :(得分:-2)

html:

<div class="parent"></div>
<div class="parent red"></div>
<div class="parent blue"></div>
<div class="parent green"></div>

scss:

.parent{
  width: 50px;
  height: 50px;
  background-color: black;
  &.red{
    background-color: red;
  }
  &.blue{
    background-color: blue;
  }
  &.green{
    background-color: green;
  }
  &:hover{
    background-color: yellow;
  }
}

[我用钢笔书写了如何实现此目的] [1]

[1]: https://codepen.io/anon/pen/RmdzWE

是的,您可以对所有元素应用相同的悬停效果