Friday 15 January 2016

Sass_Ampersand

The & is an extremely useful feature in Sass (and Less). It's used when nesting. It can be a nice time-saver when you know how to use it, or a bit of a time-waster when you're struggling and could have written the same code in regular CSS.

Let's see if we can really understand it.

Basic Nesting

SCSS
.parent{
  .child{}
}

CSS
.parent .child{}

You can nest as deep as you'd like, but it's a good practice to keep it only a level or two to prevent overly specific selectors (which are less useful and harder to override).

Add another class

The & comes in handy when you're nesting and you want to create a more specific selector, like an element that has *both* of two classes, like this:

SCSS
.some-class{
  &.another-class{}
}

CSS
.some-class.another-class{}

The & always refers to the parent selector when nesting. Think of the & as being removed and replaced with the parent selector.

"Ahh" moment

SCSS
.parent{
  & .child{}
}

.parent{
  .child{}
}

CSS
.parent .child{}

The example with the & isn't anything different than the example without the&. Nesting without the & is shorthand for nesting with it. We can think of the &as a mechanism that allows us to place the parent selector wherever we need it in our child selector. It allows us to nest with alterations. Let's look at some more examples.

Using the & with pseudo classes

You can write pseudo classes on a class in a much less repetitive way with the &:

SCSS
.button{
  &:visited{}
  &:hover{}
  &:active{}
}

CSS
.button:visited{}
.button:hover{}
.button:active{}

Using the & with >, + and ~

SCSS
.button{
  & > span{}
  & + span{}
  & ~ span{}
}

CSS
.button > span{}
.button + span{}
.button ~ span{}

Read More

No comments:

Post a Comment