How to use function and mixin in Sass

When working with Sass both function and mixin is a handy feature that allows for advanced functionality.
This article just covers the basics, it's recommended to read the official documentation found under Links.
How to use function and mixin in Sass

Content

  1 Intro
  2 @function
  3 @mixin
  4 In use
    Links

Intro

In this example we're going to define a color palette and a mixin for defining the body and child tag.

@function

The function getColor($name) returns the color with matching name.
This file contains a color palette used to create matching colors on a site.

The function getColor($name) is used to return colors from map $colors in _Colors.scss
1
$colors: ( Main: #9a2601, Light: #f2af53, Link: #a74829, Even: #f7f2e8, Odd: #ede3d0, Tech: #4cd00f );
2
3
@function getColor($name) {
4
    @return map-get($colors, $name);
5
}
6
                            
$colors: ( Main: #9a2601, Light: #f2af53, Link: #a74829, Even: #f7f2e8, Odd: #ede3d0, Tech: #4cd00f );

@function getColor($name) {
    @return map-get($colors, $name);
}

                            
                        

@mixin

The mixin is supposed to define the width of a content element on a website.
Mixin's are great to reuse code in many scenarios.
The mixin bodyContent($width) supplies styling to any style who implements it.
1
@mixin bodyContent($width) {
2
    width: 100%;
3
    max-width: $width;
4
    margin: auto;
5
}
                            
@mixin bodyContent($width) {
    width: 100%;
    max-width: $width;
    margin: auto;
}
                            
                        

In use

In this example the mixin uses values from the function getColor($name) and the mixin is implemented in Index.scss.
File using mixin bodyContent($width).
1
@import "Colors";
2
@import "Mixin";
3
4
body {
5
    background-color: getColor(Light);    
6
    color: getColor(Main);
7
8
    & > div.content.small {
9
        @include bodyContent(600px);
10
    }
11
12
    & > div.content.large {
13
        @include bodyContent(1024px);
14
    }
15
}
16
17
a {
18
    color: rgba(getColor(Link), 0,7);
19
    text-decoration: none;
20
21
    &:hover {
22
        color: getColor(Link);
23
        text-decoration: underline;
24
    }
25
}
26
                            
@import "Colors";
@import "Mixin";

body {
    background-color: getColor(Light);    
    color: getColor(Main);

    & > div.content.small {
        @include bodyContent(600px);
    }

    & > div.content.large {
        @include bodyContent(1024px);
    }
}

a {
    color: rgba(getColor(Link), 0,7);
    text-decoration: none;

    &:hover {
        color: getColor(Link);
        text-decoration: underline;
    }
}

                            
                        

Comments

Name