Animating Pseudo Elements with CSS

If you’ve ever tried to animate or transition a CSS pseudo element you’ve probably run into the sad fact that modern browsers lack proper support (for reference, Chris Coyier has made a support table available here). Even with ongoing discussions on both the Chrome and Webkit bug trackers, no fixes or implementations look close to landing, anytime soon (both tickets were filed over 2 years ago).
Our MediaEverywhere platform, currently in development, happens to utilize a number of icons in the UI that are all generated using either the :before or :after pseudo elements. That known, we were forced to find a way to animate these elements that would work cross browser and with the least amount of overhead.

Our solution, which was discovered by one of our Senior Javascript Engineers (Shane Jonas), involves animating the element itself and not the pseudo element independently. To some, that may be a deal-breaker. For us, it’s exactly what we needed.

To start, getting the transition to work required nesting content within the element itself, like so:

<

span

class

=

“icon”

>

&

nbsp

;

span

>

At first, we opted to nest a non-breaking space (as above), but this lead to inconsistent spacing that would ultimately need to be offset. This was definitely not ideal. After further investigation, we found the best way forward would be nesting an empty child element instead.

<

span

class

=

“icon”

>

<

span

>

span

>

span

>

Although not the cleanest solution markup-wise, we wanted to defer as much overhead as possible while still gaining the desired functionality (and this seems to fit those criteria). From there, we hide the nested element with CSS to maintain consistency:

.

icon

span

{

display

:

none

;

}

Overall, we’re happy with this solution. For a limited amount of effort we now get cross-browser support for CSS animations and transitions of pseudo elements. In the future, we’re hoping to rid ourselves of this technique once proper support is in place. For now, we’re hoping this solution will help others who may have run into similar issues and are looking for creative alternatives.

Here’s a quick demo of our completed solution in action (hint: hover over the snowman):

If you’d like to hear more about the work we’re doing here at Polar Mobile or about the MediaEverywhere platform, feel free to follow us @PolarMobile or put your name on the waiting list for our upcoming JavaScript meetup.