Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding z-index: How does this element appear in front of its parent's sibling?

Tags:

html

css

z-index

Why is the red div in front of the green div when I remove z-index from .wrapperRed?

It feels like z-index is inherited up the chain.

If I change the z-index of the green div to 6, it stays in front of the red one even after removing the line described in the first sentence.

.wrapperRed {
  height: 200px;
  width: 200px;
  position: absolute;
  z-index: 1; /* Why is the red div in front of the green one, if this z-index is deleted? */
}

.red {
  position: absolute;
  height: 100%;
  width: 100%;
  background-color: red;
  z-index: 5;
}

.green {
  height: 200px;
  width: 200px;
  background-color: green;
  position: absolute;
  top: 100px;
  left: 100px;
  z-index: 1;
}
<div class="wrapperRed">
  <div class="red"></div>
</div>
<div class="green"></div>
like image 629
evaenrique Avatar asked Jul 11 '16 15:07

evaenrique


People also ask

Does Z index place the element behind its parent?

The z-index of elements inside of a stacking context are always relative to the parent's current order in its own stacking context. The <html> element is a stacking context itself and nothing can ever go behind it. You can put stuff behind the <body> until you create a stacking context with it.

How do you make a child element lower the Z index than the parent?

How to get a child element to show behind (lower z-index) than its parent? is to: Make the parent not a stacking context. Make the child a positioned stacking context , whose z-index smaller than 0.

Does Z index affect children?

the z-index default is auto which states "Sets the stack order equal to its parents". However, using z-index on the child will move it out of the natural stack order and place it behind the background.

What is the Z index function and how does it work?

The z-index CSS property sets the z-order of a positioned element and its descendants or flex items. Overlapping elements with a larger z-index cover those with a smaller one.


1 Answers

When you remove z-index from .wrapperRed, the element defaults to z-index: auto.

In this case, both .red and .green participate in the same stacking context because positioned elements do not create a stacking context when z-index is auto (reference).

Learn more about z-index and stacking contexts here: Basics of the CSS z-index property

like image 189
Michael Benjamin Avatar answered Oct 14 '22 02:10

Michael Benjamin