SASS placeholder Tutorials with Examples


Placeholders in SASS enables to declare group of rules as base styles and  extend those styles into other classes, This enables DRY (don’t repeat your code) principle for modular design.

@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 base class with default styles
  • Created a extended styles for error,info,success,warn buttons  with additional styles
  • Extended styles using @extend directive with place holder
%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 above sass styles are compiled, 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 

To use @extend directive in media queries are tricky. if you extend the selector which is outside of media query always gives 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.
To understand better, First understand the rules declaration inside media queries

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

output css will not generated, 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;  
  }  
}  

Similar Posts