Mike Bertelsen Mike Bertelsen - 1 year ago 52
CSS Question

Sass .scss: Nesting extra class on div

I'm trying to display a

div
with a simple
display:none/block
. When a button is clicked, I append an
.active
class to my
div
.

I wan't to target this
.active
class using SASS, but I can't do it if I try to nest it.

HTML:

<div class="MyDiv">
I'm a hidden div. But when some button is clicked I get the class Active
</div>


Javascript

$(".MyDiv").on("click", function() {
$(this).toggleClass("active");
});


CSS: (What I expect after SASS compiles)

.MyDiv {
display:none;
}

.MyDiv.active {
display:block;
}


SASS

.MyDiv {
display:none;

.active {
display:block; /* this one doesn't work */
}
}

Answer Source

When you write the way you are writing, it compiles to .MyDiv .active which is not what you want, you need to use &.active so your selector will be .MyDiv.active

.MyDiv {
  display: none;

  &.active {
    display: block;
  }
}