﻿Border radius Sass Mixin with code example

Border radius Sass Mixin

One of the coolest features of using SASS is the ability to create a mixin.

Mixins allow us to take a chunk of CSS and reuse that CSS in other parts of our style sheet.

In this example I will be focusing on mixin border-radius, Mixins give us a considerable amount of power over how we can style your CSS files and if used correctly, can reduce the amount of work we need to do.

There are many ways you can convert Sass into CSS; for this blog, I am using Bootstrap Studio.

Converting Sass to CSS does not come out of the box in Bootstrap Studio, you have to take several steps before you can use SASS, which is out of the scope of this blog, but if you want to know how to set-up SASS in Bootstrap Studio, please view this blog.

Let's start creating our .scss file; one will be called main.scss and the second will named mixins.scss.

Code for mixins.scss:

The points to note about the code below is how we can import other .scss files into our sass files; then create a class or id depending on your requirements and @include our code from the mixins file.

Running the code above will output the following CSS:

At first glance, it not that impressive, but think about what we have just achieved; we have passed parameters to an external file that took those parameters and then converted the file into CSS.

Sass Mixins

Let's take this one step further, at the moment we are hardcoding the border thickness, type of border and colour, but we can change that and add parameters in our mixin file so that we can easily change the border thickness and colour to suit our needs.

Now create a new .scss file and call it colours.scss and add the following code:

Now change the code in our mixins.scss file to match the code below:

We can import that file into our main.scss file and once done, you should have the same as below:

Those of you with a sharp eye may have noticed some changes to the .main.scss file and the mixins.scss file. The border-radius class now only passes in the border thickness, border style and border colour, which, when compiled to CSS, produces the following:

Now that is the power of Sass; we can create one mixin and pass in different parameters and change the look of the element which uses it. Not only that, we can skip some parameter thus reducing the amount of CSS created.

The image below shows how the HTML will look in the browser.

You have to admit, that is cool.

Thank you for taking the time to read this blog.

Leave a comment