cfree
cfree

Reputation: 333

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

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/

Upvotes: 6

Views: 9932

Answers (2)

nice ass
nice ass

Reputation: 16719

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)

Upvotes: 13

rninty
rninty

Reputation: 1082

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?

Upvotes: 2

Related Questions