Maciej S.
Maciej S.

Reputation: 1903

Should I always nest selectors in other selectors when using sass?

My question is about nesting in sass or scss. It is a good thing from the readability perspective that we can nest selectors inside another selectors in sass but is it something that we must do? I am a little bit confused because when I run scss-lint, then I'm getting some errors nesting depth. I red a few articles and now I know that we should go deeper than nesting more than 3 rules one inside another.

So I have two questions:

  1. Is there anything wrong if I will write my rules in sass just like this (without nesting):

    .my-class ...

Instead of writing like that:

header
    nav
        .myclass
  1. Can you explain why is it necessary to nest in sass and what are the advantages of nesting? I know that it is good for overriding rules, but if I don't need to nest that deep? I will appreciate any answers or even links to some articles explaining my questions in more detail.

Upvotes: 2

Views: 1732

Answers (1)

jwfrench
jwfrench

Reputation: 230

You should actually avoid nesting selectors in Sass if you don't have good reason to. See Avoid Nested Selectors for more Modular CSS and Beware of Selector Nesting in Sass for why you should be more selective about nesting.

Regarding your formatting, what you're doing is functionally equivalent to nesting, but you really shouldn't be formatting your line breaks and indentations to mimic nesting when that's not what your intent is.

header
  nav
    .myclass {...}

and

header {
  nav {
    .myclass {...}
  }
}

both produce:

header nav .myclass {...}

So even though scss-lint might be getting tripped up by your formatting, it's probably not something you want to be doing anyway. And if you simply aren't concerned with your nesting or selector depth, just disable or override the linters.

Upvotes: 2

Related Questions