Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

z-index stack doesn't work right [duplicate]

Tags:

html

css

#twitter{
  width:50px;
  height:50px;
  position: absolute;
  right: 0%;
  bottom: 0%;
  background-color: orange; 
  z-index:-2;
}

#socialButton {
  position: relative;
  width: 80px;
  height: 80px;
  background-color: green;
  z-index: 2;
}

#socialButtonRoot {
  width: 100px;
  height: 100px;
  top:20%;
  left:20%;
  position: absolute;
  background-color: hotpink;
  z-index: 5;
}
<div id="socialButtonRoot">
  <div id="socialButton">
    <div id="twitter"></div>
  </div>
</div>

This is a simplified version.

In my react project there's component created some Dom nodes, after that I set the styles for them in the CSS file, most styles works fine, but only the z-index style doesn't work, people said we should set the position, yes I've all of them set, but it still doesn't work. So I think it maybe something to do with React or JS, but after I extracted code from React and JS and test it on jsfiddle, z-index still doesn't work. Then, I changed changed the z-index value from 2 to "2" (a string ) , it works, but I can see the value "2" is invalid in the chrome's debug console.

It should be div socialButtonRoot on the front which have highest z-index(5) and div socialButton in the middle which have the second high z-index(2) and div twitter in the back, which have the lowest z-index.

but in the result below, it shows, div twitter on the front and div socialButton in the middle and div socialButtonRoot on the back, which isn't right.

What's the problem here?

like image 834
cary Avatar asked Aug 07 '18 07:08

cary


1 Answers

See The Stacking Context on MDN.

A stacking context is formed, anywhere in the document, by any element in the following scenarios: … Element with a position value "absolute" or "relative" and z-index value other than "auto".

Within a stacking context, child elements are stacked according to the same rules previously explained. Importantly, the z-index values of its child stacking contexts only have meaning in this parent. Stacking contexts are treated atomically as a single unit in the parent stacking context.

The z-index positions an element inside the stacking context it is associated with.

Giving an element position: absolute or position: relative establishes a new stacking context.

Thus #twitter is positioned inside the 3-d box represented by #socialButton.

The z-index is for that box, and not for the entire document.

(And #socialButton is inside #socialButtonRoot in the same way).


If you want A to be rendered below B then either:

  • Do not position A or
  • Do not make B a descendant of A
like image 134
Quentin Avatar answered Sep 22 '22 01:09

Quentin