Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

::before pseudo-element with negative z-index not displaying behind parent

Tags:

html

css

I swear I've done this a hundred times, but for the life of me, I can't figure out why my :before pseudo-element's background is displaying behind the text but not behind the anchor's background. 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>

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

like image 603
cfree Avatar asked Nov 09 '13 22:11

cfree


2 Answers

When you add a z-index value to an element, you create a new stacking context. Every child of that element will stack on top of it.

So when you want to place an element behind its parent, simply don't create a stacking context on the parent. You still need to use a negative z-index though, because the default stack level of the parent will be 0 (in whatever context the element is)

like image 185
nice ass Avatar answered Oct 05 '22 00:10

nice ass


The ::before and ::after pseudo-elements are named a bit confusingly – they behave as if they were children of the matched element, not its siblings.

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

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

Is this the effect you were looking for?

like image 34
rninty Avatar answered Oct 04 '22 23:10

rninty