Day 14 of #100DaysOfCode!

cfalucho

Christian Falucho

Posted on July 8, 2021

Day 14 of #100DaysOfCode!

Today's progress

Continued working on SASS and learned a little bit about one key functionality of SASS which are @mixins and @include.

What I learned

@mixin allows you to create CSS code that can be reused and are defined using the syntax @mixin. They can also contain styles of their own. the @include is created to use the mixin.

Let's see how that looks like...

@mixin red-color{
  color: red;
}

h1{
  @include red-color;
}
Enter fullscreen mode Exit fullscreen mode

In the above example we created a @mixin name red-color and gave it the property color which has the value red.

Then we grab the tag name h1 and use @include on the defined mixin red-color.

Now when we compile the SASS to CSS it will make the h1 tag the color red on our CSS file.

That was a simple example of using the syntax @mixin and @include. I mentioned earlier that mixin allows CSS code to be reused and does this by passing in arguments.

Say, throughout our webpage we have different sizes of heading elements h1, h2, h3 and we want a different color for each of one. We can solve this by using mixins and passing in a different color argument.

Here's an example of that.

@mixin some-color($pick-color){
    color: $pick-color;
}

h1{
   @include some-color(red);
}

h2{
   @include some-color(blue);
}
Enter fullscreen mode Exit fullscreen mode
style.scss

When we compile the SASS to CSS it will create a h1 and h2 tag that will have the property values that we assigned it on our SASS file.

h1{
   color: red;
}

h2{
   color: blue;
}
Enter fullscreen mode Exit fullscreen mode
style.css

In Conclusion

Of course these were very basic examples of compiling SASS code to CSS code and using the functionality of @mixin and @include to create reusable code. It helps to pass in an argument with your mixin so that you can have different property values passed while using the same @mixin.

💖 💪 🙅 🚩
cfalucho
Christian Falucho

Posted on July 8, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Day 14 of #100DaysOfCode!