CSS :after behind parent element

ronnyrr picture ronnyrr · Dec 9, 2015 · Viewed 14.1k times · Source

Is it possible to get a CSS pseudo :after element behind the background of it's parent element?

The background of the :after contains equal dimensions as the parent element's background. So currently it looks like this:

enter image description here

But I want the red background (:after) to go behind the parent element. So I've added position: relative to the parent and absolute to the pseudo element.

Trying to archive this I've used this code:

The weird thing is that above snippet works like charm. But in my live example the exact same code displays as the image in this topic.. Someone knows what is wrong in the live site?

Answer

Slavenko Miljic picture Slavenko Miljic · Dec 9, 2015

You can place the :after element behind its parent if you wrap its parent inside another element. What happens is that the :after is ignoring the positioning on its parent, but it will apply positioning on the next parent in the hierarchy.

HTML

    <div class="wrap">
        <a href="" class="btn blue">
            <span>Bekijk op facebook</span>
            <span class="fa fa-arrow-circle-right"></span>
        </a>
    </div>

CSS

.wrap{
    position:relative;
    z-index:1;
}

.btn{
    /* remove position:relative; */
}

But, box-shadow solution in timothym answer, would be a bit more suitable for this specific case, not sure how would that fit with the rest of your website.