Sass and Compass Designer's Cookbook
上QQ阅读APP看书,第一时间看更新

Using multiple & signs to refer to the parent selector more than once

In the Referencing parent selectors with the & sign recipe of this chapter, you can read about how to use the & parent reference for selectors in SassScript. This recipe will show you how to use multiple & parent references.

Getting ready

Read the Installing Sass for command line usage recipe of Chapter 1, Getting Started with Sass, to find out how to install Ruby Sass. You can use the Ruby Sass compiler to compile the Sass code in this recipe into CSS code.

How to do it...

The following steps will show you that you can use the same parent selector more than once:

  1. Create a Sass template called main.scss and write down the SCSS code like that shown here into it:
    .link {
     &, .&-small {
    color: blue;
    }
    }
  2. Compile the main.scss file from the first step into CSS code by running the following command in your console:
    sass main.scss
    
  3. Now, you will find the following CSS code outputted to your console:
    .link, .link-small {
      color: blue; }

How it works...

The & parent reference may appear more than once within a selector. For each appearance, the & reference is replaced by the parent selector. This enables you to repeatedly refer to a parent selector without repeating its name.

There's more...

If the parent selector is a list of selectors, you can use the & parent reference to create a list of all the possible permutations of these selectors. The following example SCSS code will show you how this works:

a, b {
  & + & {
    color: black;
  }
}

The preceding SCSS code compiles into CSS code as follows:

 a + a, b + a, a + b, b + b {
  color: black; }