1

I am using sass for stying elements and am having confusion with the : and &:, and when it would be appropriate to use them.

what are the differences? when should we use which one?

.root{

    :first-child{
        color: green;
    }
    
    &:first-child{
        color: green
    }
}

which one is appropriate to select the first child of the root container

Abraham
  • 12,140
  • 4
  • 56
  • 92
  • FWIW, I think this question is a little different than the marked duplicate because it is also dealing with confusion regarding the :first-child pseudo-class. In regards to "which one is appropriate to select the first child of the root container" the answer is _neither_-- the first will output invalid CSS and the second will get the first-child that _is_ `.root`. What you want, in CSS, is `.root > *:first-child` -- you can achieve that in SCSS through nesting if so-desired. – Alexander Nied Aug 19 '21 at 15:38

2 Answers2

1

The ampersand & is the "parent selector" in Sass, and will append the rule that follows it to the containing parent scope. However, neither of the rules you have will work. The first...

.root{
    :first-child{
        color: green;
    }
}

...would render to the CSS...

.root :first-child{
    color: green;
}

...which would be invalid CSS, as the :first-child pseudo-class expects to be attached to an actual CSS selector.

The second...

.root{
    &:first-child{
        color: green
    }
}

...would render to CSS as...

.root:first-child{
    color: green
}

...but that rule equates to "the first of any children with the class .root should have color green," which is not what you desire.

For what you want--"to select the first child of the root container", you would want this CSS:

.root > *:first-child {
  color: green;
}
<div class="root">
  <p>some content</p>
  <div>
    <ul>
      <li>some</li>
      <li>other</li>
      <li>content</li>
    </ul>
  </div>
</div>

...which equates to "the first direct descendent of any type in a container with class of .root. This could be rewritten in sass a few different ways; with full nesting you could write it as

.root {
    >* {
        &:first-child {
            color: green;
        }
    }
}

...but I would probably simplify it to...

.root {
    >*:first-child {
        color: green;
    }
}
Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
0

It turned out that there is no : vs &:

Rather, the valid one is &:

&:first-child{
    color: green
}

and one shown below, that has : without & is invalid

:first-child{
    color: green;
}

//this one is an invalid code and doesn't work
Abraham
  • 12,140
  • 4
  • 56
  • 92