CSS in JS
Tags: javascript, css, frontend
Published: 2019-08-20 09:34:30

---
title: CSS in JS
published: true
tags: javascript, css, frontend
canonical_url: https://hellocode.dev/css-in-js
cover_image: https://www.nps.gov/articles/images/Art_1.jpg?maxwidth=1200&autorotate=false
---

I've looked at CSS in JS libraries before but there always seemed be trade-offs which have made them appear less attractive than Sass or even plain CSS. However, I have recently been playing around with [Emotion](https://github.com/emotion-js/emotion) and I'm pretty impressed so I thought I would write a quick post showing some examples of what it can do.

I've been using Emotion with React, there is a React-specific package (_@emotion/core_) which provides some additional features but I have just been using their framework-agnostic version. There are several different ways that you can use Emotion, the examples below use the method that works best for me, check out their [documentation](https://emotion.sh/docs/introduction) if you're interested in what else it can do.

## <svg aria-hidden="true" focusable="false" height="16" version="1.1" viewbox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>Basic usage

Emotion uses [tagged templates](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_templates) to create a CSS class which is then applied to the element. Here is the basic pattern for applying styles to a React component:

```js
import React from 'react'
import { css } from 'emotion'

export default function TestComponent(props) {
  return (
    <div
      className={css`
        background: blue;
        border: 1px solid red;
        max-width: 300px;
      `}
    >
      Hello
    </div>
  )
}
```

Notice that the string passed to the tagged template is actual CSS, there are no camel-cased keys, the values do not need to be wrapped in single quotes and the lines are terminated with semi-colons. At first I was disappointed because the syntax highlighting in VS Code was messed up but I added the [Babel Javascript](https://marketplace.visualstudio.com/items?itemName=mgmcdermott.vscode-language-babel) extension which formats the CSS as if it were in a _.css_ file so now it looks nice. 👍

![vs code syntax highlighting](https://hellocode.dev/syntax-29bc790a0952e988e831f0a979550e91.jpg)

If you look at the markup you can see that Emotion assigns a class to the elements with a random string appended to it.

![divs with classes](https://hellocode.dev/css_classnames-74f503558466dcf9d480016738d9a744.jpg)

This scopes your CSS to the element it is applied to so it won't leak to other components, making your styling _component-based_ as opposed to _document-based_ which fits better with the way that React apps are written. If you want to set global styles then Emotion has a [Global component](https://emotion.sh/docs/globals) you can use, and there is nothing stopping you from using a global stylesheet in addition to your component-level styles.

I started off by writing my styles straight into the JSX but things began to look messy. Fortunately it's really easy to extract the rules and move them above the JSX or even into their own file:

```js
import React from 'react'
import { css } from 'emotion'

export default function TestComponent(props) {
  const styling = css`
    background: blue;
    border: 1px solid red;
    max-width: 300px;
  `
  return (
    <div
      className={styling}
    >
      Hello
    </div>
  )
}
```

  

## <svg aria-hidden="true" focusable="false" height="16" version="1.1" viewbox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>Just like CSS

It's possible to do nested components, pseudo-classes and media queries:

```js
const styling = css`
  background: blue;
  border: 1px solid red;
  max-width: 300px;

  a {
    color: black;
  }
  &:hover {
    background: pink;
  }
  @media (max-width: 400px) {
    font-size: 12px;
  }
`
```

If you check the Emotion documentation there are some pretty clever things you can do with media queries if you have a lot of breakpoints to cater for, I won't go into it here but [take a look](https://emotion.sh/docs/media-queries) if you're interested.

## <svg aria-hidden="true" focusable="false" height="16" version="1.1" viewbox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>Just like JS

Because these are just strings you can do interpolation:

```js
const baseStyle = css`
  width: 300px;
  border: 1px solid black;
`
const green = css`
  ${baseStyle}
  background: green;
  `
const blue = css`
  ${baseStyle}
  background: blue;
`
const red = css`
  ${baseStyle}
  background: red;
`
return (
  <>
    <div className={green}>Green</div>
    <div className={blue}>Blue</div>
    <div className={red}>Red</div>
  </>
)
```

You could take this further and use functions:

```js
const baseStyle = css`
  width: 300px;
  border: 1px solid black;
`
function styles(color) {
  return css`
    ${baseStyle}
    background: ${color};
  `
}

return (
  <>
    <div className={styles('green')}>Green</div>
    <div className={styles('blue')}>Blue</div>
    <div className={styles('red')}>Red</div>
  </>
)
```

And it's not just values, any part of the string can be interpolated:

```js
const smallScreen = '@media (max-width: 400px)'

const style = css`
  ${smallScreen} {
    font-size: 12px;
  }
`
```

This is great for allowing you to set up a file of constants which can be imported into all of your modules for consistency or theming.

It's also worth remembering that the `css` function (tagged template) returns a class so you can dynamically add styles as you would with classes:

```js
const baseStyle = css`
  color: ${textColor};
`

function TagBlock(tagName) {
  const highlighted = tagSelected && css`
    color: ${highlightColor};
  `
  return (
    <span className={css`
      ${baseStyle}
      ${highlighted}
    `}>
      {tagName}
    </span>
  )
}
```

In this example the component will change the colour of the text to `highlightColor` when `tagSelected` is true.

* * *

I've only been using Emotion for a very brief time and have only scratched the surface of what it can do. Transitioning to it has been extremely easy because it offers all of the functionality of CSS but with the flexibility of JavaScript. The compositional way in which Emotion allows you to build your CSS compliments React nicely, particularly now that hooks are live. This is particularly noticeable when you reach a point where you want to extract some logic into its own component; simply cut and paste the JSX, hooks and styling out of your component and paste them into a new file.

This has just been a quick look at Emotion, I haven't tried other CSS-in-JS libraries, but I was impressed enough by my experience with it that I wanted to put together this quick post. Hopefully it's been helpful to someone!