DEV Community

Dev Diaries
Dev Diaries

Posted on

SCSS: Ampersand Rules

Explanation

Using the & after a declaration you can set a css rule to apply given that the
selector that has the & after actually applies when it is the parent of the element it is nested under. 🤔? So basically, you read the rule inside out. So in the first example you read if .parent-in-this-case & is the parent of .some-class, then apply this rule.

Why? 🧐

So why might you do this? One example is to affect a style for only ie-9 for
example and if you apply a class when a browser is ie-9 or below you can set specific styles within a block that only apply when ie-9 is the parent class on the html tag. Check the docs here.The & in scss offers a lot of power, but can also be a bit confusing so be mindful of your usage! Let's check out some examples:

# scss
.some-class {
    font-weight: normal;

    .parent-in-this-case & {
        font-style: italic;  
  }
}

That compiles to this css:

.some-class {
  font-weight: normal;
}
.parent-in-this-case .some-class {
  font-style: italic;
}

Here is some other useful ampersand usage:

.el {
    font-size: 12px;
    &:hover {
        color: blue;
    }
    &.active {
        font-weight: bold;
    }
    &--larger {
        font-size: 14px;
    }
}

That compiles to this css:

.el {
  font-size: 12px;
}
.el:hover {
  color: blue;
}
.el.active {
  font-weight: bold;
}
.el--larger {
  font-size: 14px;
}

Here you can see the convenience and power of the ampersand. If you're using something like BEM it makes it very easy and quick too add in custom elements and modifier classes.

Original Post on Dev Diaries
Instagram Post On Dev Diaries

Latest comments (0)