MeltingDog
MeltingDog

Reputation: 15424

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

I have a pseudo element I want to alter the top: of:

.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 .css() 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?

Upvotes: 2

Views: 205

Answers (1)

Kable
Kable

Reputation: 1035

: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>
</div>

css:

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

Upvotes: 1

Related Questions