Wednesday, March 22, 2017

SASS Placeholder selector %

Problem
Consider this SASS code:

.parent {
}
.child { 
  @extend .parent;
}


Compiled CSS for this will look like:

.parent, .child {
  /* Common stuff for parent and child */
}
.child { 
  /* Child specific stuff */
}


Solution
Even is .parent class is not used anywhere, it will still be included in the compiled CSS file. So the compiled CSS file becomes bigger than what is expected to be. To solve this problem, the placeholder selector '%' was introduced in SASS. They are very similar to class selectors, but instead of using a period (.) at the start, the percent character (%) is used. Placeholder selectors have the additional property that they will not show up in the generated CSS, only the selectors that extend them will be included in the output.

So .parent never goes into the generated CSS, except when you extend.

%parent {
}
.child { 
  @extend %parent;
}


Compiled CSS for this will look like:

.child { 
  /* Child specific stuff and stuff from parent */
}



No comments:

Post a Comment