BEM with SASS and: hover

What is the correct way to declare active states / focus / guidance 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 SCSS:

.card {
   &__image {
   }

   &__overlay {
   }

   &__title {
   }
}

And I want to change elements when I hover over a block. This does not work:

.card {
   &__overlay {
       display: none;
   }

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

And to write a whole .project__imagejust for this, one instance seems wrong.

Is there any other way to do this?

+4
source share
3 answers

More on interpolation: http://sass-lang.com/documentation/file.SASS_REFERENCE.html#interpolation_

SCSS:

.card {
    $root: &;

    &__overlay {
        display: none;

        #{$root}:hover & {
            display: block;
        }
    }
}

RESULT:

.card__overlay {
  display: none;
}

.card:hover .card__overlay {
  display: block;
}

PS. It is similar to the post safalia @alireza, but this way you do not need to duplicate the class name. Variable $rootdo it for you :)

+11

Sass ampersand selector .

(&) , . .

:

.card { 

    &__overlay {
        display:none;
    }

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

:

.card__overlay {
    display: none;
}

.card:hover .card__overlay {
    display: block;
}

(, ), .

+9

Alternative way:

Use a variable instead of an ampersand for the third level.

Link

SASS:

$className: card;
.card {
   &__overlay {
       display: none;
   }

   &:hover {

       .#{$className}__overlay {
           display: block;
       }
   }
}

CSS

.card__overlay {
  display: none;
}

.card:hover .card__overlay {
  display: block;
}
+3
source

Source: https://habr.com/ru/post/1618120/


All Articles