As we learned what is Sass now we will know about what are the functionalities and features provided by Sass. Variables and Mixins are some of them we will be learning about in this post.
Variables
Variables in Sass are nothing but the same as the variables in other programming languages which hold some value. Where that value can be accessed by the variable name. In Sass, we use variables to store CSS property value, attribute, color, size.
Uses:
Using variables we can define some default styling elements like primary color, default font size, and much more.
Where to use:
These variables can be used in place of property name or property value depending on the value it holds.
Syntax of Variables in Sass
$primary-color: black;
You must always use a $
symbol before as a prefix to the variable name.
How to use Variables:
p{
color: $primary-color;
}
div li{
color: $primary-color;
}
It sets all the p's and li's font color to black and if you want to change the color you need not change every individual property value by just changing the value of $primary-color
and it will make a change in all the occurrences of that variable. This is what makes Sass dynamic.
Mixins
Mixins are pretty much like object which contain a set of values in it that we will be using repeatedly.
Where to use:
Mixins are uses the DRY (DON'T REPEAT YOURSELF) concept where it is declared one and used an infinite number of times across the stylesheet.
Syntax:
@mixin UserDefinedName{
property: value;
}
Example:
@mixin AnythingToButton{
padding: 5px 15px;
border: 1px solid black;
border-radius: 5px;
}
In the above code, we are declaring a mixin, and '@' is used to declare a mixin with its name after the mixin keyword.
How to use:
li{
// We will make this list as a button
@include AnythingToButton;
}
a{
// We will make this anchor tag as a button
@include AnythingToButton;
}
'@include' is used to include that mixin in the element and the compiler will replace the line with the styling which is declared in it.