A placeholder in Sass is a special kind of selector, it's a cross over between a mixin and a class selector - in my opinion - and are not included in the CSS output. In this blog I will outline the uses of placeholders, their powerful features and also some of the drawbacks.
The first time I came across placeholders was when one of my developer colleagues suggested to use it when we were building a static HTML/CSS components for a client. We researched about placeholders and decided to adopt it in our SCSS markup.
Placeholders and usage
A placeholder is represented by a percentage symbol %
and is typically written like this:
%example-placeholder { padding: 20px; font-size: 18px; line-height: 28px; background-color: #fff; } // then we can apply it in our css class .class-one { @extend %example-placeholder; border: 1px solid #2596be; }
In the above example we created a placeholder with a set of css properties and applied it to .my-class
.class-one
by using the @extend
rule.
Let's add another class before we see how the CSS output looks like.
// scss file %example-placeholder { padding: 20px; font-size: 18px; line-height: 28px; background-color: #fff; } .class-one { @extend %example-placeholder; border: 1px solid #2596be; } .class-two { @extend %example-placeholder }
Here we have two classes, one with a placeholder and the other without. Let's have a look the CSS output.
// css output .class-two, .class-one { padding: 20px; font-size: 18px; line-height: 28px; background-color: #fff; } .class-one { border: 1px solid #2596be; }
We can learn that from the CSS output that a placeholder's properties is applied to classes that share it.
Placeholders are not included in the compiled css output, only its properties for its respected class.
We can even use a palceholder inside another placeholder like so:
%placeholder-one { margin-top: 24px; background-color: red; } %placeholder-two { @extend %placeholder-one; display: flex; flex-direction: column; }
Powerful combination of placeholders and mixins
We can use mixins inside placeholders to create some easy responsive styling. Let's look at an example.
// define some mixins for responsive design @mixin tablet { ...properties for tablet screens } @mixin desktop { ...properties for desktop screens } // define placeholders with mixins %p-default { font-size: 16px; line-height: 24px @include tablet { font-size: 20px; line-height: 28px; } @include desktop { font-size: 24px; line-height: 32px; } } // apply placeholder .blog-summary { @extend %p-default; } .nav-link { @extend %p-default; }
This way it is the combination of placeholders and mixins that allow us to re-use the same block of properties in a more efficient way.
Top comments (0)