Advancements in front-end web development have sparked an enormous community effort to improve the way we style applications. We saw an explosion of new styling technologies in 2015 after Facebook engineer Christopher Chedeau popularized the idea of writing CSS in JS in his slide deck React: CSS in JS.
The common goal of these libraries is to make UI development more modular, maintainable and scalable. The trend has been to combine HTML, JS, CSS together into "Components" which are, in theory, independent of context.
Before 2014, markup looked something like this:
<div class="
my-component // [1]
my-component--alert // [2]
">
...
</div>
// [1] Base styles
// [2] Additional styles that overwrite or extend the base
Chedeau identifies 7 problems with traditional CSS development:
- Global Namespace
- Dependencies
- Dead Code Elimination
- Minification
- Sharing Constants
- Non-deterministic Resolution
- Isolation
Facebook's React DOM/Native framework convinced a lot of developers to ditch CSS syntax in favor of JS syntax and inline styling, which looks something like this:
const alert = true;
...
<MyComponent
style={{backgroundColor: `${alert ? 'red' : 'green'}`}}
/>
// Generates inline style:
// <div style="background-color: red;" />
This was a big move in the right direction, because it brings style and functionality closer together. That makes it more maintainable and faster to onboard new developers.
This methodology comes with disadvantages.
- Inline styles don't support all of the great things CSS offers, like
media queries
andpseudo elements
. - Writing JS syntax for style-specific code is not as good of a developer experience. CSS's syntax is one of its stronger qualities.
- Your DOM gets bloated with inline style code.
An upcoming technology that I'm really excited about brings the best of both worlds: CSS syntax, fully integrated into JS components: It's called styled-components
. It has a terrible name, but it's a promising technology. It looks like this:
const MyComponent = styled.div` // [1] [2]
color: ${
this.props.alert
? 'red'
: 'green'
};
`
...
const alert = true;
...
<MyComponent {alert} />
// [1] A JS tagged literal.
// [2] Generates an unique class:
// <style>.AuTogEneRaTEd {background-color: red;}</style>
// ...
// <div className='AuTogEneRaTEd' />
The important thing to notice is that, inside the back ticks, we're using CSS syntax with JS interpolation. Not only do we get CSS syntax, we get extra features like nesting. This is very powerful. We are no longer cluttering our markup with inline styles, yet they're still closely related. It's extremely easy to maintain and understand. Instead of using classes to style our apps, we're now using props, which has been a huge architectural success with JS, and now we get it with CSS.
Further reading:
- styled-components
- Tagged literals
- If you liked this, you might also want to check out my SCSS framework.