Sass: & when defining nested classes

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

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

  li { display: inline-block; }

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

      

My project uses Sass. Nested classes are written using the 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 snippets generate the same CSS:

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 I skip it?

+3


source to share


2 answers


Both snippets generate the same CSS because you have a space after the &, but if you remove 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 it doesn't make sense in this case, so we use it when you have a class after & , for example:



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

  &.class2 { display: inline-block; }

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

      

You'll 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;
  }

      

+2


source


After studying the documentation, I found an explanation &

here . So it is basically &

a parent selector. From the doc:

It is sometimes useful to use the parent nested rule selector other than the default. For example, you may want styles for when this selector hovers or when the body of an element has a specific class. In these cases, you can explicitly specify where the parent selector should be inserted using & 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;
}

      

0


source







All Articles