Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Z-Index with different parents

Tags:

html

css

z-index

I'm having some trouble with the z-index. This is my simplified layout:

<div id="overlapper"></div>
<div id="container">
    <div id="child1"></div>
    <div id="child2"></div>
</div>

I need overlapper to appear in front of child1 but behind child2. I tried messing around with z index but it didn't work, I think because of the stacking context.

Any help please? thanks

like image 717
Neta Avatar asked Dec 06 '14 08:12

Neta


People also ask

Can a child have a higher z index than parent?

This is impossible as a child's z-index is set to the same stacking index as its parent.

Is Z index relative to 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.

Does Z index get inherited?

No, it isn't inherited. You can see it in MDN article. However, be aware that z-index sets the z-position relatively to the stacking context. And a positioned element with non auto z-index will create an stacking context.

Does Z Index work with position relative?

Note: Z index only works on positioned elements ( position:absolute , position:relative , or position:fixed ).


1 Answers

First, make sure that overlapper, child1 and child2 belong to the same stacking context.

That is, make sure container doesn't create a stacking context:

  • container must not be the root element.
  • container must have the default value for position, z-index, opacity and isolation properties:
    • position: static or z-index: auto
    • opacity: 1
    • isolation: auto

Now, make overlapper, child1 and child2 positioned elements, and add z-index as you want.

#overlapper, #child1, #child2 {
  position: relative;
  padding: 30px;
  height: 20px;
}
#overlapper {
  z-index: 3;
  background: red;
  top: 60px;
  margin-left: 20px;
}
#container {
  margin-top: -40px;
}
#child1 {
  z-index: 2;
  background: green;
  top: -40px;
}
#child2 {
  z-index: 4;
  background: blue;
  margin-left: 40px;
}
<div id="overlapper">Overlapper</div>
<div id="container">
    <div id="child1">Child 1</div>
    <div id="child2">Child 2</div>
</div>
like image 174
Oriol Avatar answered Oct 22 '22 22:10

Oriol