Vanta Logo
SPONSOR
Automate SOC 2 & ISO 27001 compliance with Vanta. Get $1,000 off.
Archived
Published
4 min read

Trevor I. Lasn

Staff Software Engineer, Engineering Manager

All You Need To Know About CSS-in-JS

An overview of CSS-in-JS and its relevance in modern web development

CSS-in-JS brings CSS to the component level, moving away from the traditional document-level styling approach.

You’ve likely come across terms like CSS-in-JS, Styled Components, Radium, and Aphrodite.

You might be wondering, “Why should I care? I’m perfectly fine with CSS in traditional .css files.”

CSS-in-JS is a topic that often sparks debate. I encourage you to keep an open mind and consider if it might enhance your workflow. Ultimately, the goal is to use tools that make you more efficient and content in your work.

Maintaining a large collection of stylesheets has always felt cumbersome to me, so I’m always looking for new approaches.

Many developers are curious about alternative styling methods. CSS-in-JS has emerged as one of the most promising concepts. Let’s explore why it might be worth trying.

What is CSS-in-JS?

import styled from 'styled-components'
// Create a Title component that'll render an <h1> tag with some styles
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: #BF4F74;
`;
// Create a Wrapper component that'll render a <section> tag with some styles
const Wrapper = styled.section`
padding: 4em;
background: papayawhip;
`;
// Use Title and Wrapper like any other React component – except they're styled!
render(
<Wrapper>
<Title>
Hello World!
</Title>
</Wrapper>
);

CSS-in-JS is a powerful abstraction over traditional CSS. It allows you to describe styles using JavaScript in a declarative and maintainable way. This approach leverages JavaScript’s capabilities to manage CSS at runtime and even server-side. It’s framework-agnostic, lightweight (around 6KB minified and gzipped), and extensible through a plugin API.

It’s important to note that inline styles and CSS-in-JS are not the same. Here’s a demonstration to clarify the difference.

The Difference

Not all CSS features can be replaced by JavaScript event handlers. For example, pseudo-selectors like :disabled, :before, and :nth-child aren’t possible with inline styles, and styling html and body tags is not supported.

However, with CSS-in-JS, you can use the full range of CSS features. Since it generates actual CSS, you can use any media query or pseudo-selector you need. Some libraries, like jss and styled-components, even add support for non-native features like nesting!

Why Not Just Stick With CSS?

Traditionally, we’ve used CSS at the document level, but modern web development revolves around components, not pages. CSS was not originally designed for a component-based approach. CSS-in-JS addresses this gap. A shout-out to Vue for handling this well, although Vue’s styles don’t have access to component state.

What Are the Benefits of Using CSS-in-JS?

  • Component-Based Thinking: Manage styles at the component level, eliminating the need to maintain numerous stylesheets.
  • Leverages JavaScript’s Power: Enhance CSS by tapping into JavaScript’s ecosystem.
  • True Isolation of Rules: CSS-in-JS ensures that styles don’t unintentionally inherit properties from parent elements, thanks to tools like the jss-isolate plugin.
  • Scoped Selectors: CSS-in-JS prevents selector collisions by generating unique class names, unlike traditional CSS, which has a global namespace.
  • Automatic Vendor Prefixing: No need to worry about vendor prefixes; they’re handled for you.
  • Code Sharing: Easily share constants and functions between your JavaScript and CSS.
  • Efficient DOM Management: Only the styles currently in use are rendered in the DOM, reducing clutter.
  • Dead Code Elimination: Unused styles are removed automatically.
  • CSS Unit Testing: You can write unit tests for your styles.

What Are the Drawbacks of Using CSS-in-JS?

  • Learning Curve: It takes time to learn this new approach.
  • Additional Dependencies: You’ll need to manage new libraries in your project.
  • Onboarding Challenges: New team members might take longer to adapt to a codebase using CSS-in-JS.
  • Challenging the Status Quo: Introducing CSS-in-JS might disrupt established workflows, though this isn’t necessarily a bad thing.

Despite these challenges, the advantages of CSS-in-JS far outweigh the drawbacks. It’s worth giving it a try!

All of these libraries offer extensive functionality, including theming, dynamic props, server-side rendering, and more.

If you found this article helpful, you might enjoy my free newsletter. I share developer tips and insights to help you grow your skills and career.


More Articles You Might Enjoy

If you enjoyed this article, you might find these related pieces interesting as well. If you like what I have to say, please check out the sponsors who are supporting me. Much appreciated!

Leadership
3 min read

Take Your Writing Seriously

It’s not just about getting the message across; it’s about doing so in a way that’s easy for others to follow. Good writing shows respect for your team and your work.

Sep 19, 2024
Read article
Node.js
19 min read

Common Causes of Memory Leaks in JavaScript

Identify and fix common JavaScript memory leaks (Node.js and Deno.js)

Aug 10, 2024
Read article
Webdev
12 min read

Frontend Security Checklist

Tips for Keeping All Frontend Applications Secure

Jul 30, 2024
Read article
Webdev
3 min read

Improve PageSpeed Insights Score with Lazy Loading Iframes

How to save bandwidth and speed up your site by lazy-loading iframes

Sep 13, 2024
Read article
Webdev
7 min read

Tips for Reducing Cyclomatic Complexity

Cyclomatic complexity is like counting how many ways a car can go. More options make it harder to drive because you have to make more decisions, which can lead to confusion.

Sep 10, 2024
Read article
Leadership
6 min read

The Monday Morning Test to Measure Engineering Team Health

Why the first day back can reveal everything about your engineering team's health

Nov 4, 2024
Read article
Webdev
4 min read

LH and RLH: The CSS Units That Make Vertical Spacing Easy

Exploring new CSS line-height units that eliminate guesswork from vertical rhythm

Dec 3, 2024
Read article
Sql
8 min read

Invisible columns in SQL

It’s a small feature, but it can make a big difference.

Aug 26, 2024
Read article
Javascript
5 min read

Precise Decimal Math in JavaScript with Fraction.js

How to handle exact decimal calculations in JavaScript when floating-point precision isn't good enough

Nov 16, 2024
Read article

Become a better engineer

Here are engineering resources I've personally vetted and use. They focus on skills you'll actually need to build and scale real projects - the kind of experience that gets you hired or promoted.

Many companies have a fixed annual stipend per engineer (e.g. $2,000) for use towards learning resources. If your company offers this stipend, you can forward them your invoices directly for reimbursement. By using my affiliate links, you support my work and get a discount at the same!


This article was originally published on https://www.trevorlasn.com/blog/all-you-need-to-know-about-css-in-js. It was written by a human and polished using grammar tools for clarity.