I know there are a lot of other questions on using transitions on CSS pseudo element but after going through a whole bunch of them I still can't get my scenario to work.
Basically, I want to add a class to an element, the class has a :after pseudo element with some content and a background. I'd like a fading effect on the :after element when adding or removing the class.
I've been trying this out in this jsfiddle and the code I have so far it this:
HTML
<div id="divA">Div test</div>
<button id="btnAdd">Add it</button>
<button id="btnRemove">Take Away</button>
CSS
div {
width: 200px;
transition: all .5s linear;
background: red;
}
.test{
background: blue;
}
.test:after{
background: #0c0;
content: "Test";
}
jQuery
$("#btnAdd").click(function() {
$("#divA").addClass("test");
});
$("#btnRemove").click(function() {
$("#divA").removeClass("test");
});
Any help and hints would be most appreciated.
Forking @NilsKaspersson answer to make it work with your requirements.
Transition means from X to Y, you can't expect it to work with newly created attributes.
Then you have to create an initial attribute, and alter it later.
Since you don't want it to be there at the beginning, just use color: transparent;
and background: transparent;
Running Demo
Code:
div {
width : 200px;
transition : all .5s linear;
background : red;
}
div:after {
transition : all .5s linear;
background : transparent;
color : transparent;
content : "Test";
}
.test{
background : blue;
}
.test:after{
background : #0c0;
color : black;
}
There are two things going on here.
1.) transition
only works when there's something to transition from. Since your :after
element is essentially created when the class test
is added to it, there's no transition going on.
2.) transition
doesn't inherit, so you'll need to declare it once again on the pseudo element.
Here's a quick n' dirty fork of your JSFiddle.
I moved the generic rules for the pseudo element to the classless div
and added a transition
to it. Then when the class test
is added to it, the background changes and it can transition from it's old value.
If you don't want the pseudo element's content
to be visible all the time, consider hiding it with opactiy: 0
and transition that to 1
, or use the transparent
color value for background
and/or color
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With