1

I have a button with a background color, and when I hover over it, it fills the overlay pseudo-element with a different background color and z-index, and with a z-index some kind of misunderstanding:

By default, everyone’s z-index is auto, but as I read in another answer, “Default z-index of any element is 'auto' with exception of html tag which has default z-index: 0. 'Auto' means that element gets z-index from its parent. ", i.e. 0.

This means that when you hover over a relative button, the pseudo-element absolutely positioned in it overlaps it with itself, since it goes lower in the code. If I set the pseudo-element z-index -1, it goes beyond the parent button and is not visible, because the button z-index is not set, but by default it is auto i.e. 0, which is greater than -1.

But then I explicitly set the button z-index: 0 and suddenly the overlay starts filling in the background of the button on hover, but the signature on the button itself is visible.

Actually, I don’t understand:

  1. If z-index is 0 by default, why does something change if you set it to 0 explicitly?

  2. How does the overlay push its background color to the button, but doesn’t touch the signature, if its z-index is -1 and the button has 0 (although 1/2 / etc does have the same effect)? How does an element with a smaller z-index selectively affect the element in front of it, replacing the background-color but not touching the signature?

Link to code:

https://jsfiddle.net/Solow/pv9x8zeq/39/

.btn {
  position: relative;
  z-index: 0;

  border: 0;
  padding: 15px 20px;
  background-color: lightgrey;
  cursor: pointer;
  color: white;

  &::before {
    content: "";
    position: absolute;
    z-index: -1;

    top: 0;
    left: 0;
    width: 0;
    height: 100%;

    background-color: dimgrey;
    transition: .5s;
  }

  &:hover::before {
    width: 100%;
  }
}
wazz
  • 4,953
  • 5
  • 20
  • 34
Alex
  • 21
  • 1
  • the important part is that z-index:auto and z-index:0 are completely different. The first one doesn't create a stacking context while the second one does. – Temani Afif Nov 09 '19 at 19:52
  • But in principle, elements with auto and 0 behave similarly: with an unspecified z-index, the lower element in the code overlaps the upper one, with an explicitly specified z-index at 0 - similarly. But with explicitly specified 0 for the button and -1 for the overlay - the second only covers the background of the first. This is puzzling. – Alex Nov 09 '19 at 20:44
  • The trick is the *stacking context*. setting a z-index (different from auto) will create a stacking context making all the element to be painted inside even with negative z-indexes. It's like the element become a container for all its child and no one can escape. With z-index:auto elements aren't trapped inside a stacking context create by the parent element and can be painted below their parent. You will find all the detail in the duplicate link – Temani Afif Nov 09 '19 at 20:49

0 Answers0