Yesterday, I wrote about how I ditched my Sass build step for vanilla CSS.
As part of that process, I ended up refactoring a lot of code in a way that made it simpler and more efficient. For example, my old Sass files were filled with code like this…
a:not(.btn):hover, a:not(.btn):active, a:not(.btn):focus, .active a:not(.btn), [aria-current="page"] { border-bottom: 0.125em solid $color-secondary; color: $color-black; @media (prefers-color-scheme: dark) { color: $color-white; } }
Sass supports media query nesting, which vanilla CSS does not. Rewritten for vanilla CSS, it looks like this…
a:not(.btn):hover, a:not(.btn):active, a:not(.btn):focus, .active a:not(.btn), [aria-current="page"] { border-bottom: 0.125em solid var(--color-secondary); color: var(--color-black); } @media (prefers-color-scheme: dark) { a:not(.btn):hover, a:not(.btn):active, a:not(.btn):focus, .active a:not(.btn), [aria-current="page"] { color: var(--color-white); } }
I had so many instance in my CSS file where I was switching from one color to another color for dark mode.
Often, white would become black, or black would become white. It was relatively trivial in Sass, but in CSS, it became tedious, especially for declarations with multiple, batched selectors like the example above.
So… I ended up creating some new CSS variables that handle the color switch automatically.
I setup a --color-{light color}-dm-{dark color}
naming pattern for these common color switches, and update them in just one place: my _config.css
file.
/* Automatic Dark Mode - Light Variants */ --color-black-dm-white: var(--color-black); --color-white-dm-black: var(--color-white); /* Automatic Dark Mode - Dark Variants */ @media (prefers-color-scheme: dark) { --color-black-dm-white: var(--color-white); --color-white-dm-black: var(--color-tertiary-dark); }
That example above then gets rewritten like this…
a:not(.btn):hover, a:not(.btn):active, a:not(.btn):focus, .active a:not(.btn), [aria-current="page"] { border-bottom: 0.125em solid var(--color-secondary); color: var(--color-black-dm-white); }
Across my entire project, this resulted in a massive reduction in CSS.
And this is another big benefit of using vanilla CSS over Sass. By no longer obfuscating the code that gets generated, you have the chance to write better, cleaner CSS.
Cheers,
Chris
Want to share this with others or read it later? View it in a browser.
0 Komentar untuk "[Go Make Things] Vanilla CSS and efficiencies over Sass"