Sass Mixins: What are They?

@mixin <name>
{
<contents>
}
<selector>
{
@include <mixin-name>
[<other rules>]}
@mixin float-left {
float: left;
}
.call-out {
@include float-left;
background-color: gray;
}
.call-out {
float: left;
background-color: gray;
}
@mixin a-button {
a {
background-color: blue;
color: white;
radius: 3px;
margin: 2px;

&:hover {
color: red;
}
&:visited {
color: green;
}
}
}
@include a-button.scss //assuming a-button.scss is the name of above mixin file.menu-button {
@include a-button;
}
.menu-button a {
background-color: blue;
color: white;
radius: 3px;
margin: 2px;
}
.menu-button a:hover {
color: red;
}
.menu-button a:visited {
color: green;
}

Mixin Variables

@mixin a-button($base, $hover, $link) {
a {
background-color: $base;
color: white;
radius: 3px;
margin: 2px;

&:hover {
color: $hover;
}
&:visited {
color: $link;
}
}
}
.menu-button {
@include a-button(blue, red, green);
}
.text-button {
@include a-button(yellow, black, grey);
}
.menu-button a {
background-color: blue;
color: white;
radius: 3px;
margin: 2px;
}
.menu-button a:hover {
color: red;
}
.menu-button a:visited {
color: green;
}
.text-button a {
background-color: yellow;
color: white;
radius: 3px;
margin: 2px;
}
.text-button a:hover {
color: black;
}
.text-button a:visited {
color: grey;
}
@mixin a-button($base: red, $hover: green, $link: blue) {
a {
background-color: $base;
color: white;
radius: 3px;
margin: 2px;
&:hover {
color: $hover;
}
&:visited {
color: $link;
}
}
}
.menu-button {
@include a-button($link: orange);
}
.menu-button a {
background-color: blue;
color: white;
radius: 3px;
margin: 2px;
}
.menu-button a:hover {
color: red;
}
.menu-button a:visited {
color: orange;
}
.menu-button {
@include a-button(darkmagenta, darkolivegreen, skyblue);
}

Variable Variables

@mixin margin-mix($margin...) {
margin: $margin;
}
.narrow-border {
@include margin-mix(1px);
}
.top-bottom-border {
@include margin-mix(3px 2px);
}
.varied-border {
@include margin-mix(1px 3px 6px 10px);
}
.narrow-border {
margin: 1px;
}
.top-bottom-border {
margin: 3px 2px;
}
.varied-border {
margin: 1px 3px 6px 10px;
}

Passing Content to Mixins

@mixin has-content {
html {
@content;
}
}
@include has-content {
#logo {
background-image: url(logo.svg);
}
}
html #logo {
background-image: url(logo.svg);
}
@mixin test-content($color) {
.test {
color: $color;
@content;
}
}
@include test-content(blue) {
background-color: red;
}
.test {
color: blue;
background-color: red;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store