Skip to content

Elevations (draft)

Marin Popov edited this page Aug 2, 2022 · 2 revisions

Mixins

Elevations

The elevations mixin accepts a map of elevations and uses it to produce CSS variables for each shadow in that map.

First, we define elevations map

$elevations: (
    small: box-shadow(0 .125rem .25rem rgba(0 0 0 / 75%)),
    medium: box-shadow(0 .25rem .5rem rgba(0 0 0 / 85%)),
    large: box-shadow(0 .75rem 1rem rgba(0 0 0 / 95%)),
);

Each item in the map has to have a name and has to make use of a box-shadow() function in order to provide the box-shadow value.

(
   small: box-shadow(0 .125rem .25rem rgba(0 0 0 / 75%)
)

To use the mixin simply include it where you need to access the produced CSS variables, for example on the :root level

:root {
    @include elevations($elevations);
}

The mixin will produce CSS variables for each shadow in the elevation map.

:root {
  --ig-elevation-small: ...;
  --ig-elevation-medium: ...;
  --ig-elevation-large: ...;
}

The newly produced CSS variables can be used in a usual way

.my-class {
   box-shadow: var(--ig-elevation-medium)
}

Elevation

You can also use the elevation mixin to include a box shadow by its name. The mixin accepts only one argument: the shadow name.

.my-class {
   @include elevation(small);
}

This will output

.my-class {
   box-shadow: var(--ig-elevation-small)
}

Functions

box-shadow

The box-shadow() function is used to sort out a list of valid only box-shadows. It accepts a list of shadows and returns a transformed list based on the value of the --ig-elevation-factor variable.

var(--ig-elevation-factor, 1);

// Input
box-shadow(
  (
    0 0 2px 3px black,
    0 6px 9px orange
  )
)

// Return
(
  0 0 calc(--ig-elevation-factor * 2px) calc(--ig-elevation-factor * 3px) black,
  0 calc(--ig-elevation-factor * 6px) calc(--ig-elevation-factor * 9px) orange
)

The transformation is done by _transform-shadow() function which Transforms the passed box-shadow list according to the elevation factor value

@function _transform-shadow($shadow) {
    $result: ();

    @each $value in $shadow {
        @if meta.type-of($value) != color and $value != 0 and $value != inset {
            $result: list.append($result, calc($factor * $value));
        } @else {
            $result: list.append($result, $value);
        }
    }

    @return $result;
}

This way using the factor variable allows us to easily modify all our shadows by changing a single value.

Elevation

The elevation function is used to return a box-shadow variable by its name. The function accepts only one argument: the shadow name

@function elevation($name) {
    @return var(--ig-elevation-#{$name});
}
Clone this wiki locally