具有SASS和:hover的BEM [英] BEM with SASS and :hover

查看:51
本文介绍了具有SASS和:hover的BEM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用带有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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆