Today I learned about the importance of the natural stacking order. I spent probably an hour scratching my head trying to figure out why my element with the z-index
of 500 wasn’t appearing on top of another element with a z-index
of -500. At first I thought it might have something to do with my CSS position
attribute not playing nicely with z-index
, but it had everything to do with the order in which elements appeared in my HTML.
As you can see in the example above, let’s assume the light grey rectangle is a <div>
with the class of container
or some encapsulating element containing three smaller elements on the same row. So, without any CSS positioning applied (relative, absolute, fixed, etc) these elements would naturally sit in this order from left to right.
For whatever reason, my z-index values weren’t being recognized. Z-index 500 elements were being tucked behind z-index -500 elements. I think the issue was, returning to the illustration above, I was offsetting element #3 by so many pixels such that it would overlap (ON TOP OF) the element number 2. But the natural stacking order of the HTML actually put element #2 on top of #3. And with my z-indexes, that wasn’t the result I was expecting.
So after a bit of research and trial and error, I actually changed the order of the elements and that was the trick that got me the result I was looking for.
Hope this helps somebody in the future.