How to position :before & :after pseudo-elements on top of each other?

Ila picture Ila · Oct 17, 2013 · Viewed 65.5k times · Source

What's the best way to position one pseudo-element directly on top of another pseudo-element?

Let's say I want to make a fancy "checkbox" appear next to label here:

What is the stacking order of the pseudo-elements? Does :before appear below or above :after- which is better suited to be the border, and which the fill?

And what is the best positioning to apply to label, label:before & label:after to get the proper positioning?

Answer

Ben Jackson picture Ben Jackson · Oct 17, 2013

:before (or ::before) is treated as the first child of the element it is being applied to, whilst :after (or ::after) is treated as the last child. Therefore, :after would naturally cover :before.

https://developer.mozilla.org/en-US/docs/Web/CSS/::before

https://developer.mozilla.org/en-US/docs/Web/CSS/::after

I imagine the best way to make sure they line up would be to use position: relative; on label and position: absolute; on the pseudo-elements along with the same values for top, bottom etc.

If you wanted to make a gradient border using pseudo-elements then you could do something like this:

label {
    position: relative;
    display: inline-block;
    padding: 0 2px;
    margin: 2px;
}

label:before {
    content:"";
    position: absolute;
    top: 0;
    left: 0;
    z-index: -1;
    width: 100%;
    height: 100%;
    background: white;
}

label:after {
    content:"";
    position: absolute;
    top: -2px;
    bottom: -2px;
    left: -2px;
    right: -2px;
    z-index: -2;
    background: linear-gradient(to bottom, #1e5799 13%, #efe22f 79%);
}

http://jsfiddle.net/QqzJg/

You might find this useful:

http://css-tricks.com/examples/GradientBorder/