The SASS Ampersand Tutorial

Richard Rembert - Sep 4 '22 - - Dev Community

The ampersand & operator is often used when nesting in SASS and is an extremely useful feature.

It can be a great time-saver, especially if you happen to be coding your stylesheets with the BEM methodology, or using any systematic naming convention for your class names.

See the following HTML:

<button class = "btn btn--red"> Click me! </button>
Enter fullscreen mode Exit fullscreen mode

Typical styling would be something like this:

.btn {
  display: inline-block;
  padding: 15px 32px;
}
.btn--red {
  background-color: #ff0000; // Red
}
.btn:hover {
  background-color: #fff; // White
}
Enter fullscreen mode Exit fullscreen mode

With the & operator we can be much more efficient:

.btn {
  display: inline-block;
  padding: 15px 32px;
  &--red {
    background-color: #ff0000; // Red
  }
  &:hover {
    background-color: #fff; // White
  }
}
Enter fullscreen mode Exit fullscreen mode

Notice that we’ve now nested the child selectors that use the same .btn name, represented by the & operator. name.

When compiled the & operator will be replaced by its enclosing selector name!

In the next post, we’ll learn about control directives.

Conclusion

If you liked this blog post, follow me on Twitter where I post daily about Tech related things!
Buy Me A Coffee If you enjoyed this article & would like to leave a tip — click here

🌎 Let's Connect

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .