Proper cross-fade in CSS
2 min read • Posted on October 6, 2022
In https://www.youtube.com/watch?v=PYSOnC2CrD8, @surma and @jakearchibald talked about what a proper cross-fade is, why it is complicated to do with the current technologies. And at the end of the video, they mentioned that they just proposed this to the CSS working group.
What is a proper cross fade?
If we want to transition from a text A
to a text B
, the easiest is to vary the opacity from 1 to 0 on A
, and from 0 to 1 on B
.
The main issue with this method is that, for instance, during the middle of the animation, both will have a 50% opacity. Due to how CSS composes layers, we’ll still have a color with 75% opacity. But in cross fade, the opacity should always be 100% as we are animating from the start to the end, without any notion of “this is on top of the other”.
Here you can see the difference between improper and proper cross fade:
Incorrect 75% opacity | Fixed version |
---|---|
How to achieve this
The way to do it is to add mix-blend-mode: plus-lighter
on the second text, so that CSS knows how to blend this layer with the other ones.
In addition to setting the mix-blend-mode
, we should add isolation: isolate
on the container so that CSS knows that the composition operation should only be computed within this element, and that we shouldn’t also apply it with the full background.
Here is the MDN article on mix-blend-mode
: https://developer.mozilla.org/en-US/docs/Web/CSS/mix-blend-mode.