Hitesh Kumar
Hitesh Kumar

Reputation: 3698

Sass: & when defining nested classes

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?

Upvotes: 3

Views: 6035

Answers (2)

Hitesh Kumar
Hitesh Kumar

Reputation: 3698

After delving into documentation I found explanation of & here. So basically & is a parent-selector. From doc:

Sometimes it’s useful to use a nested rule’s parent selector in other ways than the default. For instance, you might want to have special styles for when that selector is hovered over or for when the body element has a certain class. In these cases, you can explicitly specify where the parent selector should be inserted using the & character. For example:

SCSS:

a {
  font-weight: bold;
  text-decoration: none;
  &:hover { text-decoration: underline; }
  body.firefox & { font-weight: normal; }
}

CSS:

    a {
  font-weight: bold;
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}

body.firefox a {
  font-weight: normal;
}

Upvotes: 0

kebir
kebir

Reputation: 276

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;
  }

Upvotes: 3

Related Questions