Mixins

Mixins are used to make a set of properties reusable.

@mixin directive syntax

The mixin directive syntax is very similar to that of a function:

@mixin mixin-name([...arguments]) {
  property: value;

  selector {
    property: value;
  }
}
@mixin overlay($background-color: transparent) {
  bottom: 0;
  left: 0;
  position: absolute;
  right: 0;
  top: 0;
  background-color: $background-color;
}

.product__link-overlay {
  @include overlay;
}

.modal-background {
  @include overlay(rgba(0, 0, 0, .8));
}

The @content directive

Using the @content you can pass css properties to a mixin.

@mixin button() {
  display: inline-block;
  border-radius: 2px;
  padding: 8px 10px;
  font-size: 16px;
  text-decoration: none;
  @content;
}

.success {
  @include button {
    background: #228b22;
    color: #fff;
  }
}

.cancel {
  @include button {
    background: #778899;
    color: #f8f8f8;
  }
}

Tasks

Hint code and test in the playground

  1. Create a mixin that outputs a code for configurable flex element: allow changing direction, wrapping and content alignment
  2. Create a mixin that wraps your code in a media query:
@include phones {
    // my code
}

/*
@media screen and (max-width: 40rem) {
    // my code
}
*/

Read more

results matching ""

    No results matching ""