使用带有SASS的BEM声明活动/焦点/悬停状态的正确方法是什么?例如,我具有以下结构:
What's the proper way of declaring active/focus/hover states using BEM with SASS? For example, I have this structure:
<div class="card"> <img class="card__image" src="..." alt=""> <div class="card__overlay"> <div class="card__title"></div> </div> </div>还有SCSS:
.card { &__image { } &__overlay { } &__title { } }并且我想在将鼠标悬停在块上时修改元素.这不起作用:
And I want to modify the elements when hovering on the block. This doesn't work:
.card { &__overlay { display: none; } &:hover { &__overlay { display: block; } } }而且仅为此一个实例编写整个 .project__image 似乎是错误的.
And having to write the whole .project__image just for this one instance seems wrong.
还有其他方法可以做到这一点吗?
Is there any other way to accomplish this?
推荐答案您可以使用 Sass和号选择器,而无需使用变量或插值.
You can achieve the desired result using the Sass ampersand selector, without using variables or interpolation.
使用&号引用父选择器可以是一个强大的工具(如果使用得当).此功能有以下几种简单用法:以及该功能的一些非常复杂的用途.
Referencing parent selectors by using the ampersand (&) can be a powerful tool, if used right. There are simple uses of this feature as well as some very complex uses of this feature.
例如:
.card { &__overlay { display:none; } &:hover & { &__overlay { display: block; } } }结果:
.card__overlay { display: none; } .card:hover .card__overlay { display: block; }此代码使用较少的语言构造(例如,不使用变量或插值),因此可以说是一种更简洁的实现.
This code uses fewer language constructs (e.g. no use of variables or interpolation) and so is arguably a cleaner implementation.
更多推荐
具有SASS和:hover的BEM
发布评论