-2

Here is a simple example that draws a square in SCSS. Why does the background color only take effect when it is in .color, and not .black?

CodePen

<div class="color black"></div>

.color {
  width: 112px;
  height: 112px;
  display: block;
  // background: #000;
  .black {
    background: #000;
  }
}
evan
  • 954
  • 3
  • 18
  • 37

1 Answers1

3

Because .black thinks its a child element. So the .black part of this is looking for an element that is a child of .color.

.color {
  width: 112px;
  height: 112px;
  display: block;
  // background: #000;
  .black {
    background: #000;
  }
}

If your html looked like this

<div class='color'>
    <div class='black'></div>
</div>

Then it would work correctly.

As it is, you need an & in front of black.

.color {
  width: 112px;
  height: 112px;
  display: block;
  // background: #000;
  &.black {
    background: #000;
  }
}

This works just like you expect it to.

Bobo
  • 976
  • 2
  • 10
  • 25
  • Thank you, I forgot the `&`. And off of that answer, do you always have to use the `&` when nesting classes? – evan Aug 11 '14 at 17:31
  • If you are talking about the same element, yes. If you mean child elements, no. – Bobo Aug 11 '14 at 17:34
  • If you want a child element, you could also do `& .black` (notice the space), but that is equivalent to `.black`. Some people like to use the `&` all the time, but I find it confusing. I only use it when necessary, so if I mean to use the same element. – Bobo Aug 11 '14 at 17:35