Keyframe animations have a special role in the CSS cascade
- Published at
- Updated at
- Reading time
- 2min
I've been reading Josh's post The Big Gotcha With @starting-style
and learned a new thing about CSS @keyframes
.
Instead of doing specificity math for each built-in style, the browser treats them [the animation styles] as an entirely separate collection of CSS. They get applied first, and any CSS we write, no matter its specificity, will overwrite it.
Granted, I don't use keyframe animations very often, but what CSS collection is Josh talking about? The answer can be found on the MDN docs explaining the CSS cascade.
The cascading algorithm determines what properties to apply to an element in the following order:
- user-agent (browser) normal
- user normal
- author (developer) normal
- CSS keyframe animations
- author (developer)
!important
- user
!important
- user-agent (browser)
!important
- CSS transitions
And keyframe animations have a higher precedence than any other "non-important" style. This behavior makes it quite handy to apply entry animations.
HTML
CSS
You can apply a keyframe animation that only defines from
styles and can then automatically transition to the other applied properties. This keyframe transition works because keyframe styles are treated higher in the cascade algorithm. Well, today I learned!
If you apply !important
styles, this doesn't work for the same cascade algorithm rules.
HTML
CSS
Keyframe animations won't overrule !important
styles and slapping more !important
properties into your keyframes won't work either.
HTML
CSS
Either way, Josh argues that for the mentioned reasons, @starting-style
might be a mistake and the more I think of it, I think he's right.
Join 6.2k readers and learn something new every week with Web Weekly.