SASS

Mixin

  • use @mixin to reuse a group of css
@mixin border-radius($radius) {
border-radius: $radius;
}
#box {
width: 150px;
height: 150px;
background-color: green;
@include border-radius(15px);
}
  • use @if and @else to add logic to styles
@mixin border-stroke($val) {
@if $val == light {
border: 1px solid black;
}
@else if $val == medium {
border: 3px solid black;
}
@else if $val == heavy {
border: 6px solid black;
}
@else {
border: none;
}
}
#box {
width: 150px;
height: 150px;
background-color: red;
@include border-stroke(medium);
}
  • use @for to create loops
    • from start through end --> includes last item
    • from start to end
@for $i from 1 to 6 {
.text-#{$i} {
font-size: 15px * $i;
}
}
.text-1 { font-size: 15px; }
.text-2 { font-size: 30px; }
.text-3 { font-size: 45px; }
/...
  • use @each to map over items in a list
/* list */
@each $color in blue, black, red {
.#{$color}-bg {
background-color: $color;
}
}
/* map */
$colors: (color1: blue, color2: black, color3: red);
@each $key, $color in $colors {
.#{$color}-bg {
background-color: $color;
}
}
/* css output */
.blue-bg { background-color: blue; }
.black-bg { background-color: black; }
.red-bg { background-color: red; }
/* hmmm...when to use list? when to use map? */
  • use @while to apply a style until a condition is met
$x: 1;
@while $x < 6 {
.text-#{$x} {
font-size: 15px * $x;
}
$x: $x + 1;
}
  • use partials to split styles into smaller chunks
    • name for partials start with underscore i.e. _mixins.scss
@import 'mixins'
  • use @extend to reuse set of css styles from another element
.info{
width: 200px;
border: 1px solid black;
margin: 0 auto;
}
.info-important {
@extend .info;
background-color: magenta;
}