Is it possible to animate CSS pseudo-classes?
Say I have:
#foo:after {
content: \'\';
width: 200px;
height: 200px;
background: red;
It does not seem to work now, however according to the W3 specs you can apply transitions to pseudo-elements. Maybe some time in future…
Your fiddle does work for me in Firefox. And as far as I know, and if this article is up to date this is the only browser that can animate pseudo-elements.
EDIT: As of 2016, the link to article is broken and the relevant WebKit bug was fixed 4 years ago. Read on to see other answers, this one is obsolete.
I just found out that you can animate :after and :before (:
Code example-
.model-item {
position: relative;
&:after {
content: '';
position: absolute;
width: 100%;
height: 100%;
top: 0;
right: 0;
background: transparent;
transition: all .3s;
}
}
.opc {
&:after {
content: '';
position: absolute;
width: 100%;
height: 100%;
top: 0;
right: 0;
background: rgba(0, 51, 92, .75);
}
}
I have the div .model-item and i needed to animate his :after. So i've added another class which changes background and i added the transition code to the main :after (before animation)
Google Chrome added the webkit bug fix to Version 27.0.1453.110 m
This WebKit bug was fixed: http://trac.webkit.org/changeset/138632
IT IS POSSIBLE to animate pseudo :before
and :after
, here are a couple of examples for animating the psuedo-elements :before
and :after
.
Here is a modification of your example above with some edits, that make it animate in and out more smoothly without the simulated mouseleave
/ mouseout
delay on hover:
http://jsfiddle.net/MxTvw/234/
Try adding the main selector #foo
with the grouped :hover
pseudo-class in your second :hover
pseudo-class rule. Also add the transition
property, and not just the vendor specific prefixed properties for transition
:
#foo:after{
display: block;
content: '';
width: 200px;
height: 200px;
background: red;
-webkit-transition: all .4s ease-in-out;
-moz-transition: all .4s ease-in-out;
-o-transition: all .4s ease-in-out;
transition: all .4s ease-in-out;
}
#foo,
#foo:hover:after,
#foo:hover:before{
width: 250px;
height: 250px;
}
Note that going forward any Pseudo Elements like :before
and :after
should use the double colon syntax ::before
and ::after
. This example simulates a fade in and out using a overlay background-color
and a background-image
on hover:
http://jsfiddle.net/MxTvw/233/
This example simulates a animate of rotation on hover:
http://jsfiddle.net/Jm54S/28/
Of course moving forward with css3 standards we could use ::before
and ::after
.
This works in latest Firefox, Chrome, Safari, Opera 18+, IE10, IE11 (IE9 and below do not support css3 transitions or animate.)