ronnyrr
ronnyrr

Reputation: 1561

CSS :after behind parent element

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:

.btn {
  position: relative;
  display: inline-block;
  padding: .8rem 1rem;
  font-size: 1rem;
  background: #000;
}

.btn:after {
  position: absolute;
  bottom: -0.3rem; right: -0.3rem;
  z-index: -1;

  width: 100%; height: 100%;
  content:'';
  background: red;
}
<a href="" class="btn">
  This is my button
</a>

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?

Upvotes: 6

Views: 18392

Answers (3)

Slavenko Miljic
Slavenko Miljic

Reputation: 3856

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.

Upvotes: 5

Marc Audet
Marc Audet

Reputation: 46795

In your website, you have the following CSS rule:

.btn {
  position: relative;
  z-index: 1;
  display: inline-block;
  padding: .8rem 1rem;
  font-size: 1rem;
  background: #000;
  -webkit-transition: all 0.2s linear;
  -moz-transition: all 0.2s linear;
  -o-transition: all 0.2s linear;
  transition: all 0.2s linear;
}

If you remove the z-index: 1 property, your CSS will work correctly. This property is not in the sample snippet that you provided above.

I tried it out using CSS inspector in Firefox and that seems to fix the issue.

Upvotes: 2

timothym
timothym

Reputation: 3275

A :before or :after pseudo-element is considered a child element, and due to the stacking context of the elements, an :after element can't be displayed behind its parent in this way.

However, you can use box-shadow to create a solid 'border' that achieves the effect you are going for. Here's an example:

.btn{
  box-shadow: red 6px 7px 0 0;
}

Upvotes: 4

Related Questions