How does SASS use placeholder selectors? Usage examples

Placeholders are another special kind of selector. Use it when writing your own SASS library. It works very similarly to a mixin without parameters.

The placeholder selector starts with the % sign.

The syntax is as follows:

%( name_of_selector ) { property: value; ... }

The SASS file is compiled without a placeholder selector (which defines the main function of the file. See “Using Placeholder Selectors” below). So the question is: how to use it?

To use a placeholder selector, we use the @Extend rule.

The syntax is as follows:

@extend %( name_of_selector );

Example:

SASS Files:

%button-format {
    padding: 10px 20px;
    border-radius: 15px;
    color: black;
}

.toolbar-button {
    @extend %button-format;
    background-color: lightpink;

    &:hover {
        background-color: rgb(155, 106, 114);
    }
}

.status-bar-button {
    @extend %button-format;
    background-color: lightblue;

    &:hover {
        background-color: blue;
    }
}

Compiled CSS file:

.status-bar-button, .toolbar-button {
    padding: 10px 20px;
    border-radius: 15px;
    color: black;
  }
  
  .toolbar-button {
    background-color: lightpink;
  }
  .toolbar-button:hover {
    background-color: #9b6a72;
  }
  
  .status-bar-button {
    background-color: lightblue;
  }
  .status-bar-button:hover {
    background-color: blue;
  }

Use of placeholder selectors:

The placeholder selector is not included in the compilation of the SASS file, so it is used to create the SASS library. We can use it to predefine some templates, and then we can use it with @extend at-rule as needed, as shown in the example above.