The z-index property seems to be malfunctioning when used in conjunction with the relative and absolute positioning


I have created a dropdown menu using pure CSS3, but I am facing an issue with the z-index property. The dropdown list is appearing above the menu when it should be dropping below it. I have spent all day trying to troubleshoot this problem to no avail, so now I am reaching out for help. I have applied different background colors to highlight the problematic items and demonstrate what I am aiming for. The goal is to have the sub-menu with the red background display under the blue background.
P.S. I attempted to create this menu using jQuery slideDown/slideUp properties, but they do not provide the desired slide effect seen in my example. They appear more like stretching, which is not the outcome I desire.

SEE EXAMPLE ON JSFIDDLE

ul {
  list-style-type: none;
}
.menu_wrapper {
  position: relative;
  z-index: 999;
  /* THE Z-INDEX IS NOT WORKING... */
  height: 70px;
  width: 600px;
  background-color: blue;
}
.menu li {
  display: inline;
  float: left;
  display: table;
  height: inherit;
  margin: 3px;
  margin-top: 10px;
}
.menu li a {
  display: table-cell;
  font-family: Verdana;
  font-size: 16px;
  color: gold;
  text-align: center;
  text-decoration: none;
  padding-left: 10px;
  padding-right: 10px;
  vertical-align: middle;
  background: #05487F;
  transition: .2s ease-in-out;
}
.sub-menu {
  position: absolute;
  z-index: 1;
  /* THE Z-INDEX IS NOT WORKING... */
  margin-top: -200px;
  margin-left: -132px;
  padding: 15px;
  padding-top: 20px;
  background-color: red;
  transition: all 1s ease-in-out;
}
.sub-menu li {
  float: none;
}
.sub-menu li a {
  padding: 5px 15px;
}
.menu li a:hover + .sub-menu {
  margin-top: 40px;
}
.sub-menu:hover {
  margin-top: 40px;
}
<nav class="menu_wrapper">
  <ul class="menu">
    <li><a href="about/index.html">About</a>
    </li>
    <li><a href="news/index.html">News</a>
    </li>
    <li>
      <a href="">PROBLEM HERE<br>(HOVER THIS)</a>
      <ul class="sub-menu">
        <li><a href="">link 1</a>
        </li>
        <li><a href="">link 2</a>
        </li>
        <li><a href="">link 3</a>
        </li>
      </ul>
    </li>
    <li><a href="">Something</a>
    </li>
    <li><a href="">Contacts</a>
    </li>
  </ul>
</nav>

Answer №1

The issue arises when a stacking context is created for .menu_wrapper by assigning a z-index: 999. This prevents positioning any child element behind its parent.

To resolve this, simply remove the z-index: 999 declaration from .menu_wrapper:

.menu_wrapper {
  position: relative;
  /* z-index: 999; << Remove this line */
  height: 70px;
  width: 600px;
  background-color: blue;
}

Next, adjust the z-index value of .sub-menu to a negative number like -1:

See Updated Example

.sub-menu {
  position: absolute;
  z-index: -1;
  margin-top: -200px;
  margin-left: -132px;
  padding: 15px;
  padding-top: 20px;
  background-color: red;
  transition: all 1s ease-in-out;
}

Answer №2

Let's talk about the importance of z-index.

The concept of z-index is crucial when it comes to layering elements on a webpage. In the normal DOM flow, z-index is relative to its parent element and ultimately the Window object. However, when an element is absolutely positioned, it is taken out of the normal flow, making the z-index relative to itself rather than the Window object.

If you haven't set a position for your parent menu, it will default to position:static, which cannot be z-indexed. To ensure that your submenu appears above the parent menu, make sure to add the following CSS properties to the parent menu:

position:relative;
z-index:1;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating dynamic canvas elements with images using HTML and JavaScript

Currently, I am working on a unique project involving a canvas filled with dynamic moving balls. This project is an extension or inspired by the codepen project located at: https://codepen.io/zetyler/pen/LergVR. The basic concept of this project remains t ...

Organize the HTML output generated by a PHP array

There must be a simple solution to this, but for some reason, it's escaping me right now. I've created custom HTML/CSS/JS for a slider that fetches its content from an array structured like this: $slides = [ [ 'img' = ...

Specify the width of one element to always be the same as the width of another

One common challenge is maintaining the width of one element equal to another when the page loads (refer to link description here). However, it becomes tricky when the side width changes, such as resizing the browser window. Is there a way to dynamically ...

A guide to customizing the label color in Material-UI's <TextField/> component

How do I change the text color of the "email" label to match the border color? Below is the provided code: import React, { Component } from "react"; import { Icon } from "semantic-ui-react"; import { Divider } from "semantic-ui-react"; import { TextField ...

Non-responsive behavior triggered by a button click event (JavaScript)

Help needed with displaying results on the same page for an online calculator I'm creating. Why are the results not showing up as expected? I want users to input 4 pieces of information, have the logic executed, and then display the answers below th ...

Unsuccessful conversion of JSON data to HTML using json2html in Python

I have been experimenting with converting JSON data to HTML using json2html. The JSON data structure I am working with is as follows: json_obj = [{"Agent Status": "status1", "Last backup": "", "hostId": 1234567, "hostfqdn": "test1.example.com", "username" ...

Locate an original identifier using Selenium WebDriver

In search of a distinctive identifier for the "update profile picture button" on my Facebook account to utilize it in automation testing with Selenium WebDriver and Java. I attempted driver.findElement(By.className("_156p")).click();, but unfortunately, i ...

highcharts-ng expands in flexbox without contracting

I've encountered an issue while trying to incorporate a highchart within a flexbox container. The chart expands along with the container without any problems, but it fails to contract when the container size decreases. My current setup involves angul ...

Changing the Style of a CSS Module Using JavaScript

Embarking on a journey into Javascript and React, I am currently working on my first React app. My aim is to adjust the number of "gridTemplateRows" displayed on the screen using a variable that will be updated based on data. Right now, it's hardcode ...

Find the value of the nearest input field using jQuery

I'm working with HTML code that looks like this: <tr> <td class='qty'><input class='narrow' value='1' /><i class='fa fa-trash' aria-hidden='true'></i></td> < ...

Avoiding the inclusion of special characters in symfony css selectors, or utilizing wildcard characters for more

Currently, I am utilizing the Symfony\Component\DomCrawler\Crawler component in order to locate a form that contains a name with various CSS special characters. <input name="myfield[0].thing"> In my code, I have: $messageElement = $ ...

Including CSS in an HTML file does not function properly

I've been attempting to import a CSS file into an HTML document, but for some reason it's not working. I have also tried linking the path directly, but that hasn't worked either. <!DOCTYPE html> <html lang="en"> <head> < ...

Tips on confirming the completion of my form when the next button is pressed

I am working on a multi-step form with a jQuery script to split the forms. The first form has only one button - the next button, which takes the client to the next form. However, when I click on the next button in the first form, it moves to the next form ...

Bizarre actions with jQuery append in Internet Explorer 8

Issue with adding elements to a div in IE8: The element is not added until the button is clicked twice, resulting in two new elements being added at once. Here's the code snippet in question: $(options.addButton).click(function(event) { var proto ...

Incorporate Margins for Table Cells in Outlook (HTML Email)

I'm currently in the process of creating an email newsletter and testing it out on Litmus. Here's how the newsletter design should appear (refer to the image below): Although I understand that it may not look exactly the same on Outlook, is the ...

The Art of Dynamic Component Manipulation in Angular

The current official documentation only demonstrates how to dynamically alter components within an <ng-template> tag. https://angular.io/guide/dynamic-component-loader My goal is to have 3 components: header, section, and footer with the following s ...

Creating rounded buttons with Font Awesome icons and hover effects

I am currently working on creating buttons similar to the design shown in the image below. https://i.sstatic.net/hMqHs.png I have utilized stacked Font Awesome icons to place the icons atop a circle, resulting in this look: https://i.sstatic.net/rtEkP.p ...

Initiate an animation upon reaching a designated element using Jquery scroll event

Hey there! I've been trying to create an animation without using any plugins, but unfortunately, I haven't had much luck so far. Here's the code I've been working on. If anyone can help me figure this out, I'd really appreciate it ...

Converting an HTML form into a Django form while maintaining the original styling

I have a basic HTML form that I would like to use for collecting sign-in information with a Django backend. Below is my simple non-Django HTML form: <form id="contactForm" method="POST"> <div class="row"> <div class="form-group ...

Enlarging and cutting video footage

I have developed an app that features a code enabling users to capture photos using their computer-connected camera. How it Works: A webcam is utilized to display a video element with the camera as its source: function onSuccess (stream) { this.video.s ...