Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BEM with SASS and :hover

Tags:

css

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>    

And the 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;
       }
   }
}

And having to write the whole .project__image just for this one instance seems wrong.

Is there any other way to accomplish this?

like image 640
so4t Avatar asked Dec 01 '15 13:12

so4t


People also ask

What is the BEM methodology?

What is BEM? BEM is a front-end naming method for organizing and naming CSS classes. The Block, Element, Modifier methodology is a popular naming convention for class names in HTML and CSS. It helps to write clean CSS by following some simple rules.

What is BEM used for?

BEM (which stands for Block-Element-Modifier) is a naming convention standard for CSS class names. It has fairly wide adoption and is immensely useful in writing CSS that is easier to read, understand, and scale.

What the BEM?

What is BEM? BEM stands for Block, Element, and Modifier. It's a CSS naming convention for writing cleaner and more readable CSS classes. BEM also aims to write independent CSS blocks in order to reuse them later in your project.


Video Answer


1 Answers

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.

For example:

.card { 

    &__overlay {
        display:none;
    }

    &:hover & {
        &__overlay  {
            display: block;
        }   
    }
}

Results in:

.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.

like image 85
aaronmarruk Avatar answered Oct 12 '22 03:10

aaronmarruk