OptimCommerce Blog

Z-Index – How To Put Elements Above Others

4 minute read - - May 4, 2019

Z-Index is a way to organize the stuff of your web page in the “3rd” dimension. It allows for popups for example, to appear above everything else.

A great summary of Z-Index:

“Using z-index appears extremely easy: a single property, assigned a single integer number, with an easy-to-understand behaviour. However, when z-index is applied to complex hierarchies of HTML elements, its behaviour can be hard to understand or predict. This is due to complex stacking rules.”

Mozilla Blog

First Things First

  • Z-Index is a CSS Property.
  • CSS is a way to style your HTML.
  • HTML is what makes up your web pages.

The CSS Conflict

The most common conflict that can happen is a popup that doesn’t properly cover the screen.

This is an example situation:

Z-index popup css
Popup with the menu getting in the way

In CSS, this is most likely what’s going on:

Popup and Header Z-Index
Menu is beating the popup by 1 in the z-index contest

Z-Index is a math game. Whoever has a higher z-index, gets to be on top.


The (Simplified) Solution

Let’s say this was the CSS for the menu and the popup:

#menu{
z-index: 99;
}

#popup{
z-index: 98;
}

Flipping the numbers would (generally) get you the right outcome:

The menu and popup have learned to co-exist.

Putting It Into Practice

Putting this theory into practice can be tricky at times, it’s usually not that simple with 2 elements that respect each other’s z-indices.

Here are the top 5 articles we found that cover popular, practical scenarios:

Optim Cart - Sticky Add To Cart

Optim Feed - Facebook Product Catalog