MeltingDog MeltingDog - 6 months ago 8x
Javascript Question

How to dynamically alter the CSS of a pseudo element with JQuery?

I have a pseudo element I want to alter the


.content:after {
top: 30px; //this will change

The amount of change is variable and retrieved with JQuery:

var $position = $(this).offset().top;

I know you cannot use
to alter a pseudo elements CSS and that the preferred method is to toggle an existing class. But that wont work with as rules in my class would be dynamic.

I am a little stuck as to how to go about this. Would anyone have any suggestions?


:after is equivalent to adding a child element to the end of the selected element. So if it's possible, you could move the styling to a new child element which you will be able to alter with JQuery. So your html would look like:

<div class="content">
    ... other content ...
    <div class="content-after"></div>


.content > .content-after {
  top: 30px;