[css-transitions] Proposal: a way to restrict transitioning to specific state changes
Problem
I run into this problem surprisingly often: I have a property, let's say color, that changes at specific user interactions (e.g. :hover), in which case I want the change to be animated. So I set transition: color 1s. But I also want the value of color to be different at different breakpoints, in which case I do not want the change to be animated. How can I fix that? I could set transition: none in the media query, but what if I want to keep being able to transition the color on interaction at every screen size, and only change the idle/hover colors? I can restrict the transition: color 1s to the :hover rule, but then the color will change instantly when moving the cursor away from the element.
Here's a CodePen showing the issue. And just so it's 100% clear, here's a video:
https://github.com/user-attachments/assets/3dc96252-6798-4dd2-8531-71f0dbbace83
I want to keep the transitions between blue and orange and between green and red, but NOT the transition between blue and green (the one that occurs while resizing). I want it to switch instantly between blue and green.
Solution
A new transition-scope property that accepts, for each transition-property, an identifier that needs to match between state changes for the transition to actually occur. Then, the above CodePen would work with a single CSS addition:
a {
transition-scope: desktop;
}
@media (width < 1024px) {
a {
transition-scope: mobile;
}
}