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 reserached about placeholders and decided to adopt it in our SCSS markup.
Placeholders and usage
A placeholder is represented by a percentage symbol %
and it is typically written like this:
%example-placeholder {
padding: 20px;
font-size: 18px;
line-height: 28px;
background-color: #fff;
}
.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
by using the @extend
rule.
Let's add another class before we see how the CSS output looks like.
%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.
.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.
@mixin tablet {
...properties for tablet screens
}
@mixin desktop {
...properties for desktop screens
}
%p-default {
font-size: 16px;
line-height: 24px
@include tablet {
font-size: 20px;
line-height: 28px;
}
@include desktop {
font-size: 24px;
line-height: 32px;
}
}
.blog-summary {
@extend %p-default;
}
.nav-link {
@extend %p-default;
}
This way it is the combination of placeholders and mixins allows us to re-use the same block of properties in a more efficient way.