Layer elements with z-index using CSS

When elements overlap each other on a web page, the z-index-property can be used to specify which element should appear on top. The z-index property is a CSS property that sets the stack order of an element.

Elements with higher z-index values display in front of those with lower z-index values.

Syntax:
The syntax for using the z-index property is as follows:

selector {
  z-index: value;
}

The value can be any integer value, positive or negative. The default value for z-index is 0.

Usage Examples:
Here are some examples of how to use z-index in HTML with CSS:

1. Set an image on top of another element:

HTML:
<pre>
<div class="container">

<img src="image.jpg" alt="Image" />
<div class="content">

<h1>Title</h1>

Content

</div>
</div>

CSS:

.container {
  position: relative;
}
img {
  position: absolute;
  z-index: 1;
}
.content {
  position: relative;
  z-index: 2;
}

2. Set a dropdown menu on top of other content:

HTML:

<nav>
<ul>
 	<li style="list-style-type: none;">
<ul>
 	<li><a href="#">Home</a></li>
</ul>
</li>
</ul>
<ul>
 	<li style="list-style-type: none;">
<ul>
 	<li><a href="#">About</a></li>
</ul>
</li>
</ul>
<ul>
 	<li style="list-style-type: none;">
<ul>
 	<li class="dropdown"><a href="#">Products</a>
<ul class="dropdown-menu">
 	<li style="list-style-type: none;">
<ul class="dropdown-menu">
 	<li><a href="#">Product 1</a></li>
</ul>
</li>
</ul>
<ul class="dropdown-menu">
 	<li style="list-style-type: none;">
<ul class="dropdown-menu">
 	<li><a href="#">Product 2</a></li>
</ul>
</li>
</ul>
&nbsp;
<ul class="dropdown-menu">
 	<li style="list-style-type: none;">
<ul class="dropdown-menu">
 	<li><a href="#">Product 3</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
&nbsp;
<ul>
 	<li style="list-style-type: none;">
<ul>
 	<li><a href="#">Contact</a></li>
</ul>
</li>
</ul>

</nav>

CSS:

.dropdown-menu {
  position: absolute;
  z-index: 1;
}

External Link:
Learn more about z-index property from the Mozilla Developer Network: https://developer.mozilla.org/en-US/docs/Web/CSS/z-index.

  Written by: Steven Iversen     05-06-2023     Written in: CSS tutorials

One comment

  • Paige says:

    Wow, I never knew layering elements using z-index existed! I’ve tried it on my website and it really solve some issues for me.

Leave a Reply

Your email address will not be published. Required fields are marked *