Skip to content

Sass: Placeholder Selectors

How to use Sass placeholder selectors with the % syntax and @extend directive to efficiently reuse styles without duplicating CSS code.

SASS supports placeholder selector using class or id selector. In normal CSS, these are specified with # or ., but in SASS they are replaced with %. To work with placeholder selector, they can be used with @extend directive. Without using @extend directive, you cannot display the result in CSS.

Example

Example of placeholder selectors in a SCSS file:

<html>
   <head>
      <title>Placeholder Selectors</title>
      <link rel="stylesheet" type="text/css" href="style.css" />
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
   </head>

   <body>
      <h1>First Heading</h1>
      <p class="frst_para">First paragraph</p>
      <h1>Second Heading</h1>
      <p class="sec_para">Second paragraph</p>
   </body>
</html>

and the style.scss file:

.frst_para {
   color: green;
}
.sec_para {
   @extend .frst_para;
   font-size:20px;
}

Then you tell Sass to watch the file and update the CSS when the file changes:

sass --watch my\path\style.scss:style.css

The generated style.css files is as shown below:

.frst_para, .sec_para {
   color: green;
}
.sec_para {
   font-size: 20px;
}
Navigation