When was the last time you see the z-index
CSS property being used like so:
.some-element {
z-index: 99999999;
}
Now suppose you want another element to be displayed above the element with the "some-element" class, a quick and dirty (yet seemingly common!) fix for this is by adding another '9' at the end of the z-index value above and apply it to this other element. For bigger web apps, this can quickly become unmanageable.
Since the default ordering is determined by the order of the HTML markup, with the element nearest the bottom appearing on top, shouldn't we use that instead of z-index? Can you think of a use case where relying on the markup's order alone is insufficient?
Top comments (5)
Pretty much every widely used CSS framework that provides toasts, modals, popovers, tooltips, or anything similar uses the
z-index
property extensively, because they can't make assumptions about markup order, because they can't assume that things that are supposed to be on top in the z-axis are at the end of the markup, especially when multiple conditionally visible elements are involved, and even more so if one or more of them are dynamically added to the DOM.Bootstrap's handling of buttons also comes to mind as a good example. They use small single-digit
z-index
values to cause buttons to display or hide borders correctly relative to immediate siblings based on state. So, for example, if you have a group of three buttons touching each other and click the first one, it will properly display the border over top of the second button because it's selected.This is a great counter-argument, and seems applicable too when you have to build generic components to follow your own design system. Not using z-index would mean tying to implementation details (of how the markup appears) and making them less flexible.
Thanks for your insight - I thought there would be a valid use case for it, but couldn't think of anything to prove my colleague wrong when they thought z-index should never be used. Now that gives me some food for thought!
A follow-up question: do you know by any chance how z-index affects things like keyboard accessibility? For example, will elements with a higher z-index be reached first when navigating with keyboard tabbing?
I'm actually not sure. I suspect that higher
z-index
values will be earlier in the tab order, but only if they're explicitly called out (because tab order, unless overridden, normally follows markup order). Regardless, it's not something I would think you should rely on if it does, because then seemingly innocent changes to the CSS could drastically change the page from the perspective of someone using the keyboard to navigate.Preach! Educating myself on how to make the markup more accessible is going to be one of those ongoing goals of mine :)