Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Namespaces and maps

When there are many mixins, their names start to clash: both you and an imported library may have a .button(). A namespace is a container rule that holds mixins; from outside you reach them through the container's name. A map is a set of "key: value" pairs in one variable, for example all colours of a theme.

A namespace

Declare the #ui container in styles/mixins.less. The parentheses after the name keep it out of the CSS:

// styles/mixins.less
#ui() {
  .button() {
    padding: 8px 16px;
    border: none;
    border-radius: 8px;
  }
 
  .card() {
    padding: 16px;
    border: 1px solid #e5e7eb;
  }
}

Call the mixins through the container's name:

// styles/components/buttons.less
.btn {
  #ui.button();
}
// styles/main.less
@import "mixins";
@import "components/buttons";
.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 8px;
}

The notation #ui > .button(); does the same — you will meet it in older code, for example in Bootstrap 3 (#gradient > .vertical()).

Maps

A variable can be assigned a set of declarations in braces. Then a single value is reached by its key in square brackets:

// styles/variables.less
@colors: {
  primary: #2563eb;
  danger: #dc2626;
  text: #111827;
}
// styles/main.less
@import "variables";
 
.btn-primary {
  color: white;
  background: @colors[primary];
}
 
.alert-danger {
  color: @colors[danger];
}
.btn-primary {
  color: white;
  background: #2563eb;
}
.alert-danger {
  color: #dc2626;
}
<style>
  .btn-primary {
    color: white;
    background: #2563eb;
  }
  .alert-danger {
    color: #dc2626;
  }
</style>
 
<button class="btn-primary">Save</button>
<p class="alert-danger">Fill in the post title.</p>

This keeps the whole palette in one variable instead of ten. In Sass a map is written in parentheses, and a value is taken with the map.get() function.

A mixin as a map

A key can also be a variable inside a mixin. This is handy when settings are grouped by theme:

// styles/variables.less
#theme() {
  @radius: 8px;
  @gap: 16px;
}
// styles/main.less
@import "variables";
 
.card {
  padding: #theme[@gap];
  border-radius: #theme[@radius];
}
.card {
  padding: 16px;
  border-radius: 8px;
}

Common mistake

If you declare a namespace and a mixin inside it without parentheses, you get an ordinary nested rule, and it reaches the CSS:

// styles/mixins.less
#ui {
  .button {
    padding: 8px 16px;
  }
}
#ui .button {
  padding: 8px 16px;
}

An extra #ui .button rule appeared in the CSS. Put parentheses on both the container and the mixins inside: #ui() and .button().

Thanks for reading!

Donate to the site — we work hard for you.