You are using an outdated browser. Please upgrade your browser to improve your experience and security.

CSS-in-JS – The Component Takeover

Since CSS first came into existence over 20 years ago most websites have evolved into complex applications that require us to constantly revise our approach. There’s been many developments in its time to allow easier scaling of projects and a more consistent approach to styling. However the rise of JavaScript frameworks over the last couple of years has thrown a new spanner in the works causing a divide in opinion.

CSS in JS has come about in response to the component-based approach of these frameworks. It refers to including our styles within our components and writing them in a JavaScript syntax allowing the developer to use native JavaScript features in their styling. There’s a common misconception that this means inline styling – while in some cases this may be true – inline styling does not allow use of pseudo classes and some of the other more useful features of CSS.

The upside of CSS-in-JS

The downside of CSS-in-JS

CSS-in-JS Libraries

There are many libraries available that aim to make writing your styles straight into your JavaScript components as easy and flexible as possible. The most popular of these libraries is ‘styled-components’ (which is used by the likes of Lego and Vogue amongst many other huge household names). It is supposedly for people who ‘like’ CSS and allows developers to write styles in the same way they are used to, just inside a .js file. In second place in the popularity stakes is Emotion, they are incredibly similar and have an almost identical API as well as share pretty much all the same features. Below are examples of the syntax used in each.

The styled-components way

const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;

The emotion way

const titleStyles = css({
fontSize: ‘1.5em’,
textAlign: ‘center’,
color: ‘palevioletred’

render(<h1 className={titleStyles}>Hiya!</h1>)

There’s always going to be opposition to a new way of doing things, and in this case I don’t think either side is right or wrong. CSS in JS has its place, and to me, that is in a component heavy JavaScript project in which it feels natural to work in this way. While many see CSS-in-JS as something all on its own, I view it more as one evolution of CSS that has branched off and is great in specific cases. Every project is different, and therefore will require an approach that is suited to it and your team.

Enjoyed that? There’s more below

Let's Go

Keep me informed

What we do with your info.

This is a test message