An Incredibly Easy Way to Manage Layers in SCSS

seibmacdaniel

Mac Daniel

Posted on September 28, 2019

An Incredibly Easy Way to Manage Layers in SCSS

If you’ve come across websites that uses 0, 1, 999, 99999, 9999999 as z-index values, then you’ve probably already guessed that the layers have been arbitrarily arranged and therefore poses the imminent headache of maintaining those websites in the future.

The way I manage layers is thru SCSS placeholders. Assuming I have a couple of layered components to deal with, I extend a placeholder with the same class name but prefixed with %layer-.

.nav{
// some properties
    @extend %layer-nav;
}
.dimmer{
    // some properties
    @extend %layer-dimmer;
}
.modal{
    // some properties
    @extend %layer-modal;
}

Then, in a separate SCSS partial called _layers.scss, I lay these placeholders down, each in a one-liner manner so I can easily glance over the layers and their corresponding values.

%layer-nav  { z-index: 10; }
%layer-dimmer   { z-index: 11; }
%layer-modal    { z-index: 12; }

I also don’t mind extending the placeholder in different components first before declaring them because the compiler shall indicate some errors which I use to easily encode them in the layers partial file later on.

And that’s pretty much it. Because z-index values are implemented as placeholders, we don’t need to constantly revisit components just to adjust the values. We also don’t have to put a lot of comments to note how one thing affects another. And most importantly, we don’t have to jump tens and hundreds (or even thousands) of units just to make sure a box appears on top!

It’s also worth noting that in this implementation of @extend, sharing the same placeholder across multiple components may not be the best idea because of the naming convention.[EDIT] You're better off using variables in this case, as pointed out in the comments below.

I hope you guys find this useful as I have. Let me know what you think or if there’s an even easier way, feel free to share. I’ll be sure to check it out.

💖 💪 🙅 🚩
seibmacdaniel
Mac Daniel

Posted on September 28, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related