z-indexing: A Sneaky Complicator!

Sometimes elements overlap, and this can cause some serious problems.

Normally, elements are positioned in the order that they’re created in html. That’s called static positioning. But let’s say you have a navigator bar that’s unusual. And maybe you’re just starting out and the only way you can get your nav bar to stay in place is to give it an absolute position. (Meaning, no matter what other elements are on the page, the position of the navigator bar stays in the place you put it. Useful? Yes. Best practice? I’m not sure yet.)

So, you’ve got your absolutely positioned nav bar. Then you go and put a paragraph on the page. Since it’s statically positioned, it shows up on top of the nav bar. (This is what we in the eyeball industry would call not pretty.) So you move it down the page by giving it a top margin, great!

But.. then the bottom links in your nav bar don’t work. Wha…?!?

As you might have guessed, the combination of static positioning + absolute positioning = headache. When elements overlap, the z-index, which determines the order of overlapping elements, is by default set to the static order.

So, if your nav bar was created first, followed by your paragraph, the browser automatically gives preference to your paragraph over your nav bar. To fix, set your nav bar’s z-index to a number higher than the number of elements currently overlapping it. In my case, I’ve only got the one paragraph. Nevertheless, I set the z-index to 4 (just in case).

Note: z-index can only be set for elements that have a position of absolute, relative, or fixed.