100daysofcode - Day16
Hello friends , a new day is here and some new information is required to wrap up this day successfully .
In yesterday’s post, we talked about some amazing concepts in SASS, starting with a deep dive into the variable concept, how we use variables and all the related information about them. Then we moved on to a new interesting topic, the mixins where we made a gentle intro about it.
In today’s post , we will continue our tour to learn more about mixins , and how to use them to write some reusable pieces of code .
First of all let’s review quickly what mixins are in SASS ?
- In SASS mixin names are like any other identifier, where any hyphen or underscore are treated the same. In simple terms if we define a mixin called bullets_list and another one named bullets-list. Both of them are treated the same.
Arguments in mixins ?
-
A Sass mixin can take arguments which allow the developer to change the behavior of the defined mixin each time it gets called. Any argument can be added after the mixin name, as a list of variables surrounded by parentheses.
Example :@mixin rtl($property, $ltr-value, $rtl-value) { #{$property}: $ltr-value; [dir=rtl] & { #{$property}: $rtl-value; } } .sidebar { @include rtl(float, left, right); }
Optional arguments in mixins ?
-
Every argument declared in a mixin must be passed when this mixin is included. But there is a way to make this argument an optional one by giving it a default value which will be used if the targeted argument isn’t passed.
Example :@mixin replace-text($image, $x: 50%, $y: 50%) { text-indent: -99999em; overflow: hidden; text-align: left; background: { image: $image; repeat: no-repeat; position: $x $y; } } .mail-icon { @include replace-text(url("/images/mail.svg"), 0); }
Arbitrary arguments in Sass mixins
-
A very powerful option, can extend the functionality of a mixin in Sass, if we can pass any number of arguments to it.
-
Can this happen ? : yeah, in a sass mixin if the last variable end with 3 dots …, then all extra arguments to that mixin are passed to that argument as a list, and this argument is called the argument list.
Example :@mixin order($height, $selectors...) { @for $i from 0 to length($selectors) { #{nth($selectors, $i + 1)} { position: absolute; height: $height; margin-top: $i * $height; } } } @include order(150px, "input.name", "input.address", "input.zip");
And now after exploring the different ways to deal with a mixin in Sass. It’s time to wrap up our post, stay tuned for tomorrow’s post which will talk about a new interesting topic in Sass which is the functions .