:: before a pseudo-element with a negative z-index that does not display behind the parent

I swear I did this a hundred times, but for life I canโ€™t understand why my background :before pseudo-elements is displayed behind the text, but not behind the background anchor. Thoughts?

 .button { background: tomato; padding: 10px 30px; margin: 20px 0; display: inline-block; } .button:hover { margin: 18px 0 22px 2px; position: relative; z-index: 2; } .button:hover:after { position: absolute; background: red; top:-2px; left: -2px; content: ""; z-index: -10; width: 100%; height: 100%; } 
 <a class="button" href="#">Meow</a> 

Example here: http://jsfiddle.net/cfree/hnKLr/

+6
source share
2 answers

When you add a z-index value to an element, you create a new stacking context. Each child of this element will be placed on top of it.

Therefore, when you want to place an element behind a parent, simply do not create a stacking context for the parent. You should still use a negative z-index, though, since the default stack level for the parent will be 0 (this element in any context)

+11
source

The pseudo-elements ::before and ::after are called a little confusingly - they behave as if they were children of the matching element, and not its siblings.

In this particular case, it seems that box-shadow would be most appropriate:

 .button:hover { box-shadow: -2px -2px 0 red; } 

Is this the effect you were looking for?

+2
source

Source: https://habr.com/ru/post/957759/


All Articles