The beauty of CSS mixins
21 points by carlana
21 points by carlana
I had been asking and fighting for mixins for a decade now.
I am so happy we finally got composition in CSS. This is the kind of stuff that give me back hope in software.
Thank you to everyone involved in bringing them to life.
The --mobile and --desktop mixins sound immediately useful to me.
I would like to set my own aliases for different screen sizes, but because CSS variables aren't allowed within media query declarations I'm not able to do so. Currently, I'm forced to write out @media (width < 768px) every time which is cumbersome and error-prone. If there is a workaround I'm not aware of it.
A quick web search tells me that there have been various motions over the years to make this possible in CSS but none have landed. Here's hoping maybe this one does.
If it’s just a media query, custom media queries seem rather more appropriate and quite a bit simpler: (specified for some years and supported by various tooling for as long, but not implemented in any browser yet)
@custom-media --mobile (width < 40rem);
@custom-media --tablet (40rem <= width < 64rem);
@custom-media --desktop (width >= 64rem);
.sidebar {
@media (--mobile) {
display: none;
}
@media (--tablet) {
inline-size: 12rem;
}
@media (--desktop) {
inline-size: 20rem;
}
}
Mixins only prevail where what you want isn’t a single media query, such as this modification of one proffered example:
@mixin --if-dark-mode {
@media (prefers-color-scheme: dark) {
:root:not(.light) & {
@contents;
}
}
:root.dark & {
@contents;
}
}