loading...

re: Share your CSS knowledge VIEW POST

FULL DISCUSSION
 

I LOVE absolutely positioned ::before and ::after pseudo-elements. I usually use them to either draw lines underneath elements or additional boxes the full size of the element, which you can do wackier things to (like transforms) than using things like borders or background colors.

Example of an underline for a link:

.link {
    position: relative;
}

.link::after {
    /* 'content' value is required - this is just blank */
    content: ""; 
    position: absolute;
    display: block; 

    /* matches the width of the nearest position: relative parent */
    width: 100% 
    height: 2px;

    /* anchor it to the bottom-left corner */
    bottom: 0;
    left: 0;

    background-color: purple;
}

I use them all the time, so I set up a little SASS mixin to save some keystrokes and clean up my code:

/* the mixin (simplified version) */
@mixin pseudo($type) {

    content: "";
    position: absolute;
    display: block;

    if($type == width) {
        width: 100%;
    }
}

/* the code above with mixin */
.link {
    position: relative;

    &::after {
        @include pseudo(width);
        height: 2px;
        bottom: 0;
        left: 0;
        background-color: purple;
    }
}

Once you start playing around with them you'll find there's all kinds of fun stuff you can do without having to change the HTML at all!

Code of Conduct Report abuse