1

&.class vs & .class: Is placing a space in between make a difference?

In my sass file I have this code:

.parentClass {
  &.childClass {}
}

They want me to put a space in between the childClass and '&' symbol:

.parentClass {
  & .childClass {}
}

Does that make any difference?

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
user1176111
  • 111
  • 1
  • 11

2 Answers2

8

The difference is this:

.parentClass {
  &.childClass {}
}

will actually generate the selector .parentClass.childClass, meaning that you are selecting for an element that has both classes, e.g. <div class="parentClass childClass">. This is likely not the case you want. Meanwhile, this:

.parentClass {
  & .childClass {}
}

will compile to:

.parentClass .childClass {}

...which will select an element with the class childClass that is a child of an element with the class parentClass, e.g.:

<div class="parentClass">
    <div class="childClass"></div>
</div>

As @deceze has pointed out, in your simplified example the & is not necessary, if all you want is to imply a hierarchical relationship, because it is syntactically identical to:

.parentClass {
  .childClass {}
}

...which also gives you .parentClass .childClass {}.

Terry
  • 63,248
  • 15
  • 96
  • 118
  • …which makes the `&` in `& .childClass` redundant really. – deceze Jun 28 '19 at 06:32
  • @deceze In OP's simplified example, definitely :) however, if OP wants to filter the selector based on any other additional condition on the parent class, then the `&` will be necessary, e.g. `&[title="foo"] .childClass` ;) – Terry Jun 28 '19 at 06:33
  • Sure, only in the `&...` case is it redundant. – deceze Jun 28 '19 at 06:35
  • *that is a child of an element* No. It will select an element that is a **descendant**, it doesn't have to be a child (which would require the `>` child selector). Otherwise, good answer. – connexo Jun 28 '19 at 08:27
2

For the second case, there is no significance of putting "&" symbol because

.parentClass {
  & .childClass {}
}

and

.parentClass {
  .childClass {}
}

will result in same compiled CSS as:

.parentClass .childClass {
}
Ashish Kumar
  • 401
  • 4
  • 11