The Wonderful World Of %PlaceHolders

RobertJinChun
2 min readMay 13, 2019

--

Photo by Anas Alshanti on Unsplash

In this post, I will introduce an application for %placeHolders as an alternative for using @mixins.

For starters, lets look at a pretty nice scss example:

.box {
width: 100px;
height: 100px;
}

.box1 {
background-color: red;
}

.box2 {
background-color: blue;
}

.box3 {
background-color: green;
}

If we were to add the class of .box to .box1, .box2, .box3, we are successfully able to create three boxes with a width and height of 100px with an assortment of background colors. Great!!! Our code is dry and all we had to do is add a classs of .box to all four boxes in the HTML.

Lets say we were unable to change out markup? What would we do?

We have two options, @mixins, and %placeholders.

Lets try using a @mixin to solve our problems.

The synax to create @mixins are as follows: @mixin nameOfMixin () {}. To call created @mixin, we use :@include nameOfMixin;

Lets look at a similar example we used above:

@mixin box (){
width: 100px;
height: 100px;
}

.box1 {
background-color: red;
@include box;
}

.box2 {
background-color: blue;
@include box;
}

.box3 {
background-color: green;
@include box;
}

This piece of code compiles in our css file as:

.box1 {
background-color: red;
width: 100px;
height: 100px;
}

.box2 {
background-color: blue;
width: 100px;
height: 100px;
}

.box3 {
background-color: green;
width: 100px;
height: 100px;
}

When we compile our code, it appears as though every time we call our @mixin, it “pastes” the called code to wherever we need it. Without changing our markup, this gets the job completed, however, our code is not really DRY.

We solve this problem by using %placeHolders. Lets consider the similar example as above but instead by using a %placeHolder:

%box {
width: 100px;
height: 100px;
}

.box1 {
background-color: red;
@extend %box;
}

.box2 {
background-color: blue;
@extend %box;
}

.box3 {
background-color: green;
@extend %box;
}

The above code compiles to:

.box1, .box2, .box3{
width: 100px;
height: 100px;
}

.box1 {
background-color: red;
}

.box2 {
background-color: blue;
}

.box3 {
background-color: green;
}

With %placeHolders, we are able to solve the problem we had when we were using @mixins. Amazing!!!

--

--

RobertJinChun

Front-end developer || #Hackeryou Cohort 22 || Rock Climber Not crazy, not rich… but I am asian.