Make Sure Your Element Has The Highest Z-index

November 11, 2017 by Andreas Wik

Here is a simple way to get the highest z-index used on the page and assign a higher one to the element you need to ensure is “on top” of everything else.

This could be especially handy to use if you would build a little plugin for other web designers to place on their page, where you would have no idea what the z-index of different elements on the page is.

Now, let’s say you have a menu which will pop up like a layer over the whole screen with a dark background. Now imagine there is an info box or something at the top of the page with a z-index higher than your menu’s. It will stay visible, the menu wouldn’t be on top of it.

Like this, have a look at this demo.

To solve it, this piece of jQuery will loop through every div (add more elements to loop through those as well) and checks the z-index of it (if any), and once the loop is finished assigns a higher z-index to our menu.

$(document).ready(function() {
  var highest_z_index = 0;
  var current_z_index = 0;
  // Loop through each div and get the highest z-index
  $('div').each(function() {
    current_z_index = parseInt($(this).css("z-index"));
    if(current_z_index > highest_z_index) {
      highest_z_index = current_z_index+1;
  // Apply a higher z-index to my menu element
  $('#menu').css('z-index', highest_z_index);

And now it works! The menu is on top. Look:

See the Pen Make sure element has the highest z-index by Andreas Wik (@andreaswik) on CodePen.

Share this article

Recommended articles