Sass Reference
Article
By Hugo Giraudel

Null

By Hugo Giraudel

The null data type contains a single value in the whole Sass language: null. Thus, this value is also its type: null is the only value of type null.

This value is commonly used to define an empty state, neither true or false, or of any other value for that matters. This is typically the value you want to set when defining a variable without a value, only to prevent the parser from crashing.

null and case

null has to be lowercase for it to be from null type; NULL or any variant containing uppercase letters is from type string.

.foo {
  content: type-of(null); // null
  content: type-of(NULL); // string
}

null and length

Note that like any value in Sass, null has a length of 1 when passed to the length function. It means that a list containing null values looks like it has less values than it actually has.

$list: (foo, null, bar, null, baz);

.foo {
  content: type-of($list); // list
  content: inspect($list); // foo, bar, baz
  content: length($list);  // 5
}

null and concatenation

It is not possible to concatenate the null value with a string. When doing so, Sass throws an error:

$bar: 'foo' + null;

invalid null operation: “”foo” plus null”.

null as a CSS value

One interesting thing to know about null is that when evaluated as a CSS value, Sass will omit the declaration altogether.

$value: null;

.foo {
  // This declaration will not be output since
  // the value is evaluated as `null`
  color: $value;
}

This turns out to be quite handy when building mixins with optional output. Consider a mixin to define a position and top, right, bottom, left offsets when needed.

/// Position shorthand
/// @author Hugo Giraudel
/// @param {String} $position - Either `absolute`, `relative` or `fixed`
/// @param {Number} $top [null] - Top offset
/// @param {Number} $right [null] - Right offset
/// @param {Number} $bottom [null] - Bottom offset
/// @param {Number} $left [null] - Left offset
@mixin position($position, $top: null, $right: null, $bottom: null, $left: null) {
  position: $position;
  top: $top;
  right: $right;
  bottom: $bottom;
  left: $left;
}

What is nice with this mixin is that when not defining some offsets, they are evaluated as null, leading to the relevant properties not to be output. This means there is no need for anything like conditional statements.

Here is an example:

.foo {
  @include position(absolute, $top: 1em, left: 0);
}

This Sass snippet would be compiled to:

.foo {
  position: absolute;
  top: 1em;
  left: 0;
}

Engine compatibility

Mixins are fully compatible across all Sass engines and there is no known bug to this day about their implementation.