Sass - Placeholder Selectors



Description

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

The following example demonstrates the use of placeholder selectors in the 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">It is a CSS pre-processor which helps to reduce repetition with CSS and save the time. </p>
      <h1>Second Heading</h1>
      <p class = "sec_para">It was initially designed by Hampton Catlin and developed by Natalie Weizenbaum in 2006.</p>
   </body>
</html>

Next, create file style.scss.

style.scss

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

Here, we have used the @extend directive, which allows one selector to inherit styles of another selector. You can tell SASS to watch the file and update the CSS whenever Sass file changes, by using the following command −

sass --watch C:\ruby\lib\sass\style.scss:style.css

Next, execute the above command; it will create the style.css file automatically with the following code −

style.css

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

Output

Let us carry out the following steps to see how the above given code works −

  • Save the above given html code in placeholder_selectors.html file.

  • Open this HTML file in a browser, an output is displayed as shown below.

Sass CSS Extensions
sass_css_extensions.htm
Advertisements