In a recent project I had the opportunity to create a custom framework and while working on the structure, adding my functions, creating mixins, I decided to share some info with my fellow devs.
Here we go...
@function are blocks of code that return a single value of any Sass data type.
The function below is one that I constantly use, it takes a pixel size and converts into rem.
@function calculate-rem($size) {
$rem-size: $size / 16px;
@return #{$rem-size}rem;
}
*I could easily just use numbers but
people in the past have had the
habit of using px for all of their font sizes.
@mixin, very similar to a function but the main difference between the two is that mixins output lines of Sass code that will compile directly into CSS styles, while functions return a value that can then become the value for a CSS property or become something that might be passed to another function or mixin.
@mixin font-size($size) {
font-size: calculate-rem($size);
}
mixin is taking $size as an argument to pass into
the calculate-rem function to evaluate into rems
When using the mixin you need to use like this : @include font-size(16px)
, this will compile into font-size: 1rem;
Alternatively, i could use the function directly in my class:
.my-class {
font-size: calculate-rem(16px);
}
Placeholder are very similar to class selectors, but instead of using a period (.) at the start, the percent character (%) is used. Placeholder selectors have the additional property that they will not show up in the generated CSS, only the selectors that extend them will be included in the output.
%icon {
transition: background-color ease .2s;
margin: 0 .5em;
}
@extend allows classes to share a set of properties with one another. Selectors that @extend a class will have their selector included right up next to the class it is extending, resulting in a comma separated list.
.foo {
color: black;
border: 1px solid black;
}
.bar {
@extend .foo;
background-color: red;
}
the above compiles to :
.foo, .bar {
color: black;
border: 1px solid black;
}
.bar {
background-color: red;
}
Placeholder are meant to be used with @extend, so normally if you are aware that a set of attributes will be used across a handful of elements you can create a placeholder and extend the properties.
%icon {
transition: background-color ease .2s;
margin: 0 .5em;
}
.foo {
@extend %icon;
color: black;
border: 1px solid black;
}
.bar {
@extend %icon;
background-color: red;
}
this will compile into:
.foo, .bar {
transition: background-color ease .2s;
margin: 0 .5em;
}
.foo{
color: black;
border: 1px solid black;
}
.bar {
background-color: red;
}
This is a quick explanation on these Sass features, with enough requests i can do a second part with more advance mixins and logic. I hope you people find this useful and if you have any questions feel free to reach out in the comments or directly.
-happy to help.
Top comments (3)
Great job. This is helpful, Thanks for the write up.
This is brilliant.
thanks a lot, that's helpful π