CSS in JS
Published ....
Last modified ....
Share this post on BlueskySee discussion on Bluesky
I have been pretty vocal about writing css within javascript in the past. I used to be completely against the pattern. I believed in the power of css on its own and all the benefits of being able to use things like pseudo selectors and attribute selectors as well. So up until about a month ago I was strictly on the side of keeping css outside of the javascript files. Now I can't get enough of it.
It started with experimenting with Styled Components, which I thought was a
pretty cool idea. One of the limitations of styled components is that every dom
node starts to become a styled component. You begin to have several styled
<div>'s just to handle layout for different components. In small websites/apps
this can be an alright trade off but in larger applications this gets really
hairy really fast.
Then about two weeks ago I decided to start messing around with Next JS. With
Next comes styled-jsx which is a really cool way to handle styling components.
You simply throw a style tag within the component and add your css within a
template literal.
From here on out you can write your regular old css, include pseudo selectors and other cool things.
However one of the benefits of writing css within a template literal is the ability to inject things from within your javascript. I started with just storing my variables in separate modules like below:
export default {
a: