CSS tutorial: div over div and z-index

By , last updated November 28, 2019

We are in a constant process of making our products better. I was fixing the layout of our texture site SF Textures and faced a problem where I needed to position a shopping cart over and to the right of the top menu.

Problem

Here’s the HTML code:

<div class="menu-wrapper-custom">
	<div id="topmenu">Top Menu</div>
	<div id="texture_cart"><a href="/checkout">Checkout</a></div>
</div>

I have two div tags after each other that I need to align together. Initial code aligns the text to the right and the positioning of divs is under each other.

top menu wordpress preview aling two div css

Initial CSS code:

#menu-wrapper-custom {
}
#topmenu{
	height: 37px;
	display: block;
	padding: 0;
	margin: 0 20px 20px 260px;
	border: 1px solid;
	width: auto;
	border-color: #dddddd;
}
#texture_cart{
	text-align: right;
	position:fixed;
	right:20px;
}

That is not what I want. Here’s my goal:

css div over div in topmenu

Solution

DIV top element

In order to move the menu up I need to align the shopping cart div at the top by adding top:0px;

#texture_cart{
	text-align: right;
	position:fixed;
	top:0px;
	right:20px;
}

Now the menu looks great. Almost every time. Almost, because when I’m logged into my WordPress account I suddenly can’t see the shopping cart div any more as it is hidden behind the admin panel:

div behind admin panel in wordpress

In my case, WordPress admin panel overlaps the shopping cart. I think it’s done intentionally by WordPress as the admin panel shouldn’t be hidden behind anything.

There are several ways to fix the problem. As you can see once the admin panel has shown up the whole top menu moved down. That didn’t happen to the shopping cart.

Z index

The first and easiest way to fix hidden div is to add z-index. The z-index property specifies the order of an element. The higher the order the higher the chance that your div wouldn’t be hidden behind anything.

Fixing the admin panel over shopping cart div with z-index property requires a rather high order. This is due to the admin panel having high z-index property itself (99999):

#texture_cart{
	text-align: right;
	position:fixed;
	top:0px;
	right:20px;
	z-index:999999;
}

Now my shopping cart seems to be visible above everything:

div over div with high z-index value

And we face another problem: we can’t fully use our admin bar as some of the functions are not visible (profile editing). So the approach of adding z-index is not the most effective in this case.

DIV position element

What we want now is to set these two divs together so that they move down if something like my admin bar appears. In order to do this we need to make the parent div’s position relative. Then, we make the required div’s position absolute:

#menu-wrapper-custom {
	position:relative;
}
...

#texture_cart{
	position:absolute;
	top:0px;
	text-align:right;
	right:20px;
}

The result is fantastic:

div over div final result