{

SASS placeholder Tutorials with Examples


Placeholders in SASS enable the declaration of a group of rules as base styles and extend those styles into other classes. It enables the DRY (don’t repeat your code) principle for modular design.

Here is a syntax

  %placeholderName { 
    name: value
  }

We can use the above placeholder using the @extend directive.

@extend and placeholder selectors(%) are used to declare and extend in other styles.
SASS syntax supports sass and scss extension

Extended buttons with additional styles example

  • Created button placeholder as a base class with default styles
  • Created an extended style for error, info, success, and warn buttons with additional styles
  • Extended styles using @extend directive with placeholder
%btn {  
  border: none;  
  background-color: white;  
  cursor: pointer;  
  color: white;  
}  
  
.btn-error{  
  @extend %btn;  
  color:red;  
}  
.btn-warn{  
  @extend %btn;  
  color:yello;  
}  
.btn-info{  
  @extend %btn;  
  color:blue;  
}  
  
.btn-success{  
  @extend %btn;  
  color:green;  
}  

When the above sass styles compile, the output of CSS is as follows.

  
.btn-error, .btn-warn, .btn-info, .btn-success {  
  border: none;  
  background-color: white;  
  cursor: pointer;  
  color: white;  
}  
  
.btn-error {  
  color: red;  
}  
  
.btn-warn {  
  color: yello;  
}  
  
.btn-info {  
  color: blue;  
}  
  
.btn-success {  
  color: green;  
}  

placeholder selectors with media queries using extend directive

Using the @extenddirective in media queries is tricky.

if you extend the selector outside of the media query, It always gives an error - You may not @extend an outer selector from within @media.You may only @extend selectors within the same directive. From “@extend %heading” online.
To understand better, First understand the declaration of the rule inside media queries.

  
%heading {  
  color: blue;  
  font-size:18px;  
  
  @media (min-width: 600px) {  
    h1{  
      @extend %heading;  
    font-size:10px;  
    }  
  }  
}  

output CSS does not generate, instead got the below error

You may not `@extend` an outer selector from within @media.  
You may only @extend selectors within the same directive.  
From "@extend %heading" on line 7.  

To avoid those errors, We have to use @mixin for each selector that you want to use in media queries and extend in Media queries to use mixins.

@mixin heading() {  
  color: blue;  
  font-size:18px;  
}  
  
  
@media (min-width: 600px) {  
  h1 {  
    @include heading();  
  }  
}  

generated CSS is

  
  
.h1 {  
  color: blue;  
  font-size: 18px;  
}  
  
@media (min-width: 600px) {  
  h1 {  
    color: blue;  
    font-size: 18px;  
  }  
}  

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.