Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sass: & when defining nested classes

Tags:

css

sass

I am learning Sass. I am going through nested class section. It has following snippet.

nav {
  ul {
    margin: 0;
    padding: 0;
    list-style: none;
  }

  li { display: inline-block; }

  a {
    display: block;
    padding: 6px 12px;
    text-decoration: none;
  }
}

In my project Sass is used. And nested classes are written with the help of & operator. eg. The same snippet is written as:

nav {
  & ul {
    margin: 0;
    padding: 0;
    list-style: none;
  }

  & li { display: inline-block; }

  & a {
    display: block;
    padding: 6px 12px;
    text-decoration: none;
  }
}

Both snippet generates same CSS as:

nav ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
nav li {
  display: inline-block;
}
nav a {
  display: block;
  padding: 6px 12px;
  text-decoration: none;
}

What I want to know is what is this & operator doing here? Can it be omitted?

like image 634
Hitesh Kumar Avatar asked Jul 29 '26 06:07

Hitesh Kumar


1 Answers

Both snippet generates same CSS as because you have a space after the &, but if you delete the space you should get

navul {
  margin: 0;
  padding: 0;
  list-style: none;
}
navli {
  display: inline-block;
}
nava {
  display: block;
  padding: 6px 12px;
  text-decoration: none;
}

But in this case it makes no sense, so we use it when you have a class after the & like this:

nav {
  &.class1 {
    margin: 0;
    padding: 0;
    list-style: none;
  }

  &.class2 { display: inline-block; }

  &.class3 {
    display: block;
    padding: 6px 12px;
    text-decoration: none;
  }
}

You will get:

nav.class1 {
    margin: 0;
    padding: 0;
    list-style: none;
  }

nav.class2 { display: inline-block; }

nav.class3 {
    display: block;
    padding: 6px 12px;
    text-decoration: none;
  }
like image 124
kebir Avatar answered Jul 31 '26 23:07

kebir