Changing pseudo-elements style with JavaScript

Recently I had to add a color-picker that changed the background-color of a div and I was faced with the problem of changing a pseudo-element’s style. The div I was manipulating with JS had a :before styled to give a tilted effect, so the top of the element looked like this:

pseudo-element

If you didn’t know, styling a pseudo-element ( like :after or :before ) is quite complicated in JavaScript. You have to insert css rules directly in the page’s stylesheets and that doesn’t work ok in all browsers.

I found that the easiest way to change the background color of pseudo-elements is something very simple, instead of using:

.tilted-div:before {
    background-color: #008000;
}

You can use:

.tilted-div {
    background-color: #008000;
}
.tilted-div:before {
    background-color: inherit;
}

So now when you change the background-color using style attributes it will reflect on the :before div.

This might seem a bit obvious – but it reminds you that the inherit property can be used in a variety of situations.

Other uses

Another example in which I found this useful was with a custom bullet icon in a list. Let’s say you have this code:

.bullet-list-element {
    color: #33A880;
}
.bullet-list-element:before {
    content: "◎";
    color: inherit;
}

Now if you change the color of the text in the “bullet-list-element” it will reflect on the custom bullet added before it, which is useful especially when previewing color-changing feature something like a premium theme.