简体   繁体   中英

Z-index and background overlay

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. ", ie 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 ie 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%;
  }
}

This is because pseudo-elements are before or after content but inside an element. Check out this docs :

As their names indicate, the:before and:after pseudo-elements specify the location of content before and after an element's document tree content.

Note the key phrase at the end of this sentence, which refers to the inner content (or inner text). So, the pseudo-elements are inserted at the beginning or at the end within the specified elements' content .

Here you have an order of elements.:

button
    button::before
    content
    button::after

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM