The Sass ampersand (&) image is used to reference the mum or dad selector in a nested rule. For instance, the next targets .btn
on :hover:
.btn { ... &:hover { background: dodgerblue; } }
We will additionally place the &
after a selector to reverse the nesting order:
.btn { ... .navbar & { background: lightsteelblue; } }
This outputs a descendant selector that targets a .btn
aspect inside .navbar
:
.btn { ... } .navbar .btn { background: lightsteelblue; }
We will take this idea a step additional with an adjoining sibling combinator.
The Sass Ampersand & the Adjoining Sibling Selector
The adjoining sibling combinator (+) is used to focus on a component’s instant sibling. As an illustration:
.heading + .intro { ... }
This targets any intro
class instantly following a component with the category heading
. Let’s check out two helpful methods we are able to use this combinator with the &
selector.
Adjoining Buttons
Let’s say now we have a button group consisting of a major and a secondary motion button. Each have the category btn
.
<div class="btn-group"> <a category="btn" href="#">Main Motion</a> <a category="btn" href="#">Secondary Motion</a> </div>
The secondary motion button must be a special coloration and have a left margin to separate it from its sibling. We will use the next rule to reference btn
, then goal its instant sibling with the identical class:
.btn { ... & + & { margin-left: 15px; background: firebrick; } }
If two btn
lessons are adjoining siblings, the second will get the firebrick background and left margin. Right here’s the CSS output:
.btn { ... } .btn + .btn { margin-left: 15px; background: firebrick; }
See CodePen Demo
Columns
The adjoining &
selector additionally helps with column structure. To create a row the place all however the first column have a left margin (or gutter), we are able to write the next:
.col { ... & + & { margin-left: 30px; } }
The primary column will stay flush with the left facet of the web page, whereas the others get a roomy left margin.
See CodePen Demo
As we simply realized, the “double Sass ampersand” sibling selector is a useful resolution that retains us from writing additional CSS and lessons in our markup. Strategies like these are a number of the some ways Sass helps us write cleaner, extra environment friendly front-end code.
Study Extra Concerning the Sass Ampersand & Different Sass Fundamentals with Treehouse
Treehouse gives a variety of programs and Techdegrees that you should use to enhance your Sass abilities. Study extra about utilizing the Sass ampersand and different Sass fundamentals by signing up for a free trial of Treehouse at the moment!