Encountering problems with z-indexing when positioning a child div absolutely within a parent div that is relatively positioned

<!DOCTYPE html>
<html lang="pl">
<head>
    <title>Test z-index</title>
    <style>
        .div1 {position:relative; z-index:1; margin:10px; background:#eee; }
        .div2 {position:absolute; top:14px; z-index:999; background:blue; }
    </style>
</head>
<body>
    <div class="div1" >Lorem ipsum ... <div class="div2">This element I want to be on top!</div> Phasellus fermentum in, dolor.</div>
    <div class="div1" >Suspendisse a pellentesque dui, non felis.</div>
</body>
</html>

http://jsfiddle.net/yMcf6/

I am facing an issue with the stacking order of my CSS elements. I have two divs with the class "div1" that are relatively positioned.

Inside the first div, I placed another div with the class "div2" which is absolutely positioned. My goal is to make sure that "div2" appears on top of both instances of "div1."

Currently, "div2" is on top of the first "div1," but not the second one. How can I adjust my CSS code to ensure that "div2" remains on top of all elements on the page?

Answer №1

To allow .div2 to be positioned absolutely over the elements in .div1, you can remove the z-index from .div1.

The issue arises when each positioned .div1 with a z-index:1 creates its own stacking context, which do not interact with one another.

If you give the second .div1 its own rules, you can have:

  • first .div1 with z-index:0
  • .div1 with z-index:1
  • second .div1 with z-index:-1

This setup works due to negative z-index values being rendered and stacked below positive ones.

However, the above approach would not work if configured as follows:

  • first .div1 with z-index:1
  • .div1 with z-index:2
  • second .div1 with z-index:0

Refer to the numbered list in the documentation for an explanation of the painting order of various layers.

Answer №2

Rearrange the structure by placing div2 outside of the two div1s, eliminating the need for z-index.

For example:

http://example.com/unique-link-here

In the demonstration, I have included some padding to better illustrate that div2 is positioned on top of the other two divs.

Your HTML should be structured like this:

<div class="div1">Lorem ipsum ... Phasellus fermentum in, dolor.</div>
<div class="div1">Suspendisse a pellentesque dui, non felis.</div>
<div class="div2">This element should appear on top!</div>

Answer №3

replace div2 with top:14px; to top:0px;

This adjustment will position it above the previous line

Answer №4

Take a look at this fiddle - http://jsfiddle.net/yMcf6/10/

The issue here is that .div1 has the same z-index value for all elements within it. This means that the z-index of .div2, which is an inner element of .div1, will not affect .div2 itself. To resolve this, you can add an additional class to .div1 since it contains other elements.

For example -

<div class="div1 has_div2">Lorem ipsum ... <div class="div2">This element I want to be on top!</div> Phasellus fermentum in, dolor.</div>
<div class="div1">Suspendisse a pellentesque dui, non felis.</div>

And make sure the CSS looks like this:

.div1 {position:relative; z-index:1; margin:10px; background:#eee; }
.div1.has_div2 { z-index:5 }
.div2 {position:absolute; top:14px; z-index:999; background:blue; }

:)

Answer №5

Are you suggesting that div2 should be displayed twice?

One for each instance of div1.

Am I understanding this correctly?

Answer №6

Unfortunately, achieving this cannot be accomplished solely with CSS.

When you assign div1 a position and z-index, you establish a new stacking context. Consequently, div2 becomes nested within div1, and any z-index values inside of div1 are relevant only within that stacking context. Since the second instance of div1 and div2 exist in different stacking contexts, achieving the desired outcome is not feasible using CSS alone.

As a solution, JavaScript must be utilized in the following manner:

  • Reorder the div2 within the DOM to align with the same stacking context as div1
  • Adjust its positioning to mirror the previous arrangement
  • Assign it the appropriate z-index value

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

Anchor elements appear to overlap when in hover state

I am experiencing a challenge with creating a dropdown for the navigation menu on my mobile view. The anchors are overlapping and my attempt to stack them on top of each other using display block and margin-bottom has not been successful as evidenced by th ...

Positioning an image so that it is perfectly aligned on top of another image that is centered

http://jsfiddle.net/Weach/1/ The issue at hand involves a background image created using CSS. This image has been center aligned both horizontally and starting from the top, as visible in the provided JSFiddle link. Specifically, there is another image t ...

Widget for tracking attendance - incorporating HTML, CSS, and Bootstrap styling

I recently created a widget named attendance to track monthly data, from January to December. I spent time designing and coding it using HTML, CSS, and Bootstrap, as shown in the image below https://i.sstatic.net/FtFJv.png However, I am now faced with t ...

CSS media query to target specific viewport width

In my JavaScript code, I am dynamically creating a meta viewport. I set the value of this viewport to be 980px using the following script: var customViewPort=document.createElement('meta'); customViewPort.id="viewport"; customViewPort.name = "vie ...

Attach an object securely to a specific spot

I'm facing an issue with my product cards where the text mentioning "free shipping" is not aligned properly when there are no ratings. How can I ensure that all free shipping texts are positioned consistently on the card? Should I modify the position ...

"Implementing a responsive full-screen menu using Bootstrap for optimal user experience

I've implemented navbar-fixed-top and I want my menu items to expand to full width below the navbar when the user clicks on the burger-icon. The expanded menu should cover the entire height of the screen, and the burger-icon should transform into an ...

Angular is unable to eliminate the focus outline from a custom checkbox created with Boostrap

Have you noticed that Angular doesn't blur out the clicked element for some strange reason? Well, I came up with a little 'fix' for it: *:focus { outline: none !important; } It's not a perfect solution because ideally every element sh ...

What is the process of generating clozed text using HTML and CSS?

Is there a method to conceal text and create an underline of identical length in an HTML document? In this technique, certain highlighted words remain hidden, substituted with underlines that match the original text's length precisely. Additionally, a ...

Adjust the cell text overflow based on the width of the table

I am working with a table that has multiple columns. I want the first 3 columns to have a larger width than the others, specifically taking up 15% each for a total of 45% of the table's width. Currently, I am using this code in a sandbox environment: ...

The concept of columns nested within columns

My goal is to create three new columns within the center column on my webpage. However, when I attempt to nest them, they end up stacking at the bottom of the center column instead of staying inside it. Is there a way for the center column to act as a back ...

What can I do to prevent my website's font from getting distorted due to the recommended display settings?

I've noticed that newer laptops typically have a display font-size recommendation of 150%, which is causing issues with viewing my webpage correctly. The items appear larger and stretched out on their screens. Is there a way to ensure that users can ...

Issue with combining overflow-x, Firefox, and JavaScript

In Firefox, an issue arises that does not occur in other browsers. To see the problem in action, please visit this example page: -removed- Try selecting a page other than the home page. The window will scroll to your selection. You can then scroll down u ...

"All my online spaces are chaotic and cluttered beyond belief, overflowing with content in high-definition

One issue that frequently arises for me when developing websites is related to media queries and resolution. I have utilized the following code using a max-width of 1920px: @media only screen and (max-width : 1920px) {} However, I am facing challenges in ...

Transform @Html.PagedListPager from MVC into a structured list using Ul and LI elements

I'm currently using a paging code in my view. How can I convert this into "ul & li" tags? @Html.PagedListPager(Model, page => Url.Action("DisplayTTs", "TTCreator", new { page = page, SearchTT = ViewBag.searchTxt })) ...

How can I add margin to an anchor using CSS?

My header has a fixed height of 50px. Within the body of my page, there are numerous anchor links. However, when I click on these links, the anchored content appears underneath my fixed header, causing me to lose 50px of visible content (requiring me to sc ...

CSS file selector for Reactstrap component

What is my goal? I noticed a gap between my jumbotron and footer that I want to remove. Initially, I was able to achieve this by setting the margin-bottom to 0px, but it required passing an ID to the Jumbotron element. Now, my objective is to accomplish t ...

Using Javascript to Trigger Events on Selection

I have a unique situation: 1) One of my dropdown's choices features various car names. 2) Another dropdown has two options: When selecting each option in the second dropdown, the following should occur: a) Choose UserInput - This action will hide ...

Concealing the rear navigation button within the material carousel

I have a material css carousel, and I am trying to hide the back button on the first slide. I attempted to use the code below from a previous post The following code snippet prevents the user from looping through the carousel indefinitely. Stop looping i ...

CSS code for a fixed fullscreen menu with scrolling

I have implemented a full-screen menu that covers the entire screen, excluding the header and menu tab bar. You can view it here: https://i.stack.imgur.com/h5cQa.png On smaller screens, the entire menu cannot be displayed at once, as shown here: https://i. ...

Switch from flexbox layout to begin on the next column within the same row

I am attempting to create a CSS layout where, after a specific element like :nth-child(6), the elements will break and form a separate column within the same row. The parent element should split into 2 columns after every 6th element in the same row, then ...