CSS Has Supported Native “Mixins” For A DECADE!?!
NOTE, this is not “real world” deployable, see “Update” below
It just kind of dawned on me working on a project, and I’m surprised nobody else seems to have noticed this. It’s there. It mostly works. We have been able to use mixins in CSS for over a decade without precompilers.
Now, I’m not a fan of them in general, but there have been cases — :target
driven modal dialogs sharing code with mobile/burger menus for example — where even this old curmudgeon would find them useful. Generally I prefer to just group selectors together on shared properties, but if for example one of those properties has to be inside a media query, that’s a no-go.
So how do we do this most impossible of tasks? With keyframes! Meaning we have the chance of this working all the way back to IE10! CSS animations can behave like a mixin!
A simple example:
@keyframes testMixin {
from {
color:#F00;
padding:1rem 1rem 0;
margin:0;
}
}
h1 {
animation:1s paused testMixin;
}
@media (min-width:1rem) { /* prove it works in a media query */
p {
animation:1s paused testMixin;
}
}
It doesn’t work if you don’t set an animation time, and of course we don’t want the animation to actually run so we pause it… but boom. Mixins. Native. All the way back…