I’ve seen a lot of cool ways other developers are handling their z-index stacks recently, so I thought I would share mine. The majority of my projects utilize Sass, which features a handy data type called a map. Sass maps are essentially arrays like you would find in other programming languages, and include a list of key and value pairs. You can then use the SassScript function
map-get to lookup a value based on a specified key that correlates to the map. This concept is nothing new, but I think it works particularly well when dealing with z-index stacks.
Sass Map in Action
First, I create a Sass map, which I call
$z-layers and include it in my variables partial. Next, I create a function that takes a single parameter, the key I want to lookup from my map. Finally, any time I write a z-index property, I can pass the key to my function, which returns the value pair. You can see all of this in action over on my CodePen:
While you could name the keys in your map whatever you want, I find the use of planet names from our solar system helps to give more context to each layer. In my example, Earth is the baseline for z-index, the starting point if you will, so its value is set to 1. Moving closer to the Sun, we have Venus with a value of -1 and Mercury with a value of -99. I find that I don’t use these two very often, but they do come in handy when I need to do some weird stacking orders where some elements are behind others. On the other side of the spectrum, we have Mars with a value of 99, Jupiter with a value of 999, and Saturn with a value of 9999. The idea is that the z-index value increases the farther away you move from the Sun. I’ve found this is really easy for new developers to understand when they begin working on a project that uses this naming convention.
A couple of notes:
The last planet I include in my map is Saturn. I have yet to find a need for higher values, but you could easily expand this out based on your own project’s needs.
These values are what I’ve found useful across my own projects, but you could set them to any values that work best for you. My values are on a higher scale due to the occasional use of third party plugins, which tend to use high z-index values like 9999.
What do you use to keep track of your z-index stack? Let me know on Twitter, and feel free to grab the code and use it in your next project if you like.