DEV Community

Cover image for css-in-js
mhmd-elsaid
mhmd-elsaid

Posted on

css-in-js

Introduction

CSS-in-JS libraries have been gaining traction since component-based JavaScript frameworks appeared in front-end development.

Why we need css-in-js libraries ?

Due to the cascading nature of CSS (Cascading Style Sheets), stylesheets can load in any order and override each other in any combination.
Managing dependencies is another problem when it comes to styling SPAs (single-page application).

So

_ A well-designed CSS-in-JS library can solve all of this problems.
_ CSS-in-JS is, in fact, a JavaScript library that bundles each JavaScript component with all its belonging CSS rules and dependencies.
_ As a result, components can run independently, without relying on any external CSS file.

CSS-in-JS Libraries :

there are two types of css-in-js libraries :

Framework-Specific libraries :

libraries only work with a specific JavaScript framework.
ex :
Radium: has been created for React apps.
Styled JSX: only supports components written in JSX

Framework-specific CSS-in-JS libraries:
use the same syntax as the framework they support.

For instance:
Styled JSX uses template literals within the JSX syntax to add CSS styles to components.

const Button = (props) => (
  <button className={ 'large' in props && 'large' }>
     { props.children }
     <style jsx>{`
        button {
          padding: 20px;
          background: #eee;
          color: #999
        }
        .large {
          padding: 50px
        }
     `}</style>
  </button>
)

/* Creates a regular button */
<Button>Hi</Button>

/* Creates a large button */
<Button large>Big</Button>
Enter fullscreen mode Exit fullscreen mode

Framework-agnostic CSS-in-JS libraries:
can be used with any component-based frameworks .

for example : JSS && Emotion

example using jss

/* Registers a Web Component with red background */
import { StyleSheet, css } from 'aphrodite';

const styles = StyleSheet.create({
    red: {
        backgroundColor: 'red'
    }
});

class App extends HTMLElement {
    attachedCallback() {
        this.innerHTML = `
            <div class="${css(styles.red)}">
                This is red.
            </div>
        `;
    }
}

document.registerElement('my-app', App);
Enter fullscreen mode Exit fullscreen mode

Unique Selectors vs. Inline Styles

css-in-js libraries use one of two techniques to handle scoping :

  • unique selector: most CSS-in-JS libraries such as JSS, Emotion, and Styled Components automatically generate a unique selector for each component. In this technique library generates a unique selector such as a unique class that won’t cause any CSS specificity problems.

but this makes the source code doesn’t look very pretty.

  • inline styles: some CSS-in-JS libraries such as Radium add inline CSS on the fly to the HTML instead of generating unique classes.

adv of using inline style library:

  1. lead to more readable HTML code.
  2. better performance.
  3. source order independence.

Advantages of CSS-in-JS

  • Local Scoping:

    __ By default, CSS doesn’t allow local scoping. Each style rule has a global scope. So as a result styles can override each other in surprising ways.
    __ CSS-in-JS libraries solve this by automating scoping, which leads to a high level of predictability.

  • Encapsulation:

    __ Encapsulation facilitates maintenance and eliminates errors, as you can modify all component-related code in the same place, without having to worry about unexpectedly changing other parts of the application.

  • Portability:

    __ As components include all the source code, styles, and logic, you can securely move them around.

  • Re-usability:

    __ Components are reusable, so you only have to write them once, then you can run them everywhere.

  • Dynamic Functionality:

    __ As CSS-in-JS is essentially JavaScript code, you can apply complex logic to your style rules, such as loops, conditionals, variables, and more.

Disadvantages of CSS-in-JS

Although CSS-in-JS libraries allow you to build component-based applications in a logical and efficient manner, they also have some characteristics that might make you wary of them.

  • Extra Layer of Complexity:

    __ using css-in-js library adds an extra layer to your front-end stack, which can sometimes be unnecessary.

  • Code Readability:

    __ Automatically generated selectors significantly worsen code readability.

References:

Top comments (1)

Collapse
 
gass profile image
Gass • Edited

Thanks for the article, is very clear.

We can also experience all the advantages of CSS-in-JS by using CSS modules. I like more that approach because I can make the components cleaner. And from my perspective is good to separate styles from logic.