DEV Community

Cover image for Write Less Code with SCSS Mixins
Thushara Thiwanka
Thushara Thiwanka

Posted on • Updated on

Write Less Code with SCSS Mixins

Generally, in CSS we write a lot of redundant code in some situations. And to get around that we have to create helper classes and adding those classes to elements. To reduce effort, this is where CSS with superpowers comes in. SCSS, means Sassy CSS which known as SASS before which means Syntactically Awesome Style Sheets. SCSS is the most newer syntax and SASS is the older syntax. These are CSS preprocessors that allow us to write CSS rules more efficiently and more organized code using nesting, mixins, variables, and more. Then these rules will be compiled to CSS which the browser can understand. Here, I will walk you through how to use mixins to style a button that can change styles based on requirements.

SCSS mixins

Mixins are sets of CSS rules that can be applied to elements. These rules can be used throughout your project. Also, mixins help to modularize the code. The basic mixin structure is as below. Here, to create a mixin add any relevant name to mixin followed by the @mixin keyword then add pair of curly braces and write CSS rules inside.

Alt Text

Styling using mixins

Now, we will discuss how to add styles and include those styles in the button element. After writing CSS rules inside the mixin. we can apply those rules to any element. To add styles to the element that we want, just have to select the element and use the include and at symbol keyword along with the mixin name.

Alt TextAlt TextAlt Text

We can use mixins with variable parameters to get the most out of mixins. So that mixin will be dynamically adjustable using parameters. I will change the background and border-radius to be dynamic. In this scenario, $background and $border-radius variables passed as parameters and these variables are not mandatory to have the same name as the property but it is easier if we can have some name that indicates the property. Then when we including the mixin inside the button, we pass values as arguments. Just changing two properties we were able to achieve two different buttons using the same set of code lines.

Alt Text Alt Text

Besides that, we also can mention the default values for passed parameters then we don't have to mention arguments in each button. If we didn't pass arguments when including the mixin default values will be automatically assigned to the properties. We can assign default values as shown below.

Alt Text Alt Text

Finally, We can use this mixin throughout the whole project and generate different buttons according to requirements and this method will work for other elements as well.

Top comments (0)