8.2 C
New York
Saturday, September 18, 2021
HomeTechnologyWhat actually is CSS in JS?

What actually is CSS in JS?

CSS is essential for web projects. CSS-in-JS offers advantages that many developers find a great improvement in their work with the stylesheet language. (Photo: Sabrisy / Shutterstock)

Remember Article

CSS in JavaScript is controversial – and may well be worth a look, not just for React developers. We present the concept and formulate questions that can help you when deciding on the CSS-in-JS library.

Basically, the principle is simple: Instead of style sheets, you pack your CSS in components. Choosing the right CSS-in-JS library can be difficult with almost 50 options, and in the end it depends on your particular use case. However, all libraries have some properties in common:

Scoped CSS ✔️

All CSS-in-JS libraries generate unique names for your CSS classes, an idea that became popular with CSS Modules. All styles only affect their respective component. Styling outside the component remains completely unaffected by them and vice versa. That the names of your CSS classes collide, there are problems with the specificity or the struggle with a meaningful naming of twelve thousand CSS classes is a thing of the past. This is also the reason why developers who rely on a component-based approach – for example React – appreciate CSS-in-JS libraries so:

  
import React, {Component} from 'react';
import styled from 'styled-components';
const Background=styled.div` background: red
const Paragraph=styled.p`
color: white
`
class App extends Component {
render () {
> return (

t3n - digital pioneers


export default App;
`

In the example, here with the popular CSS-in-JS library StyledComponents for React and React Native, the styles are more or less enclosed by the component and only affect it .

No inline styles ✔️

Styles that are assigned within the HTML are called inline styles. So-called pseudo-classes, pseudo-elements and media queries are excluded with this notation. Responsive designs using inline styles are also not possible. In addition, inline styles are generally considered to be less efficient than class names. Two good reasons why most of the newer CSS-in-JS libraries have abandoned inline styles in favor of CSS class names in order to enable pseudo-classes and elements, media queries and keyframe animations.

Automatic vendor prefixes ✔️

It often takes years until new CSS features are available in all browsers due to the complex CSS standardization process. In order to make new, not yet standardized features usable in advance, non-standardized CSS syntax is delivered under a so-called vendor prefix. In older browsers, newer features are often not supported, in which case the prefixes are used. Knowing by heart which features need one for which browser is perhaps a bit exaggerated, especially since that can change over time with the release of updates and new versions. Resources like caniuse.com can be valuable sources here. Most of the CSS in JS libraries kindly relieve developers of this task. That means you can simply use the standard syntax and the library will automatically generate these properties including the vendor prefix.

Server-side rendering ✔️

Single-Page Apps or SPA come in the Usually without server-side rendering. They are traditionally rendered in the browser. Only an initial, empty HTML page comes from the http server. Websites and apps that should be parsed and indexed by search engines should have pages that are rendered on the server for a number of reasons. The same applies to so-called static site generators, where content is generated as static HTML files together with the associated CSS during build time. Most CSS-in-JS libraries support SSR so you can use them for all kinds of web projects.

Differences

So much for the similarities. In detail, the various JS-in-CSS libraries differ in several points. Some, like Styled Components or Stitches, were developed specifically for React, others – JSS, Treat, Emotion – are framework-agnostic. Most support a format that allows HTML, CSS, and JS to be in the same file, which is an advantage in many cases. This means that you can see at a glance which styling belongs to which component. In the event that the styles make a file too confusing, there is always the option to store them in a separate CSS file. Depending on the library, the styles can be defined either as a string within ES template literals or in the object styles syntax as regular JS objects. Some libraries – Styled Components, Compiled, Emotion, Goober – support both.

There are also several options for using the styles defined in this way .

The class attribute or className property -Variant

Probably the easiest way for CSS-knowledgeable developers: simply assigning styles as class names. These CSS-in-JS libraries output the class names as a string via API, which can then be assigned to HTML elements.

  // "css" is the API of a generic CSS-in-JS library here 
const heading_style=css ({
color: "red"
});
  

const heading=`

Title

`;
  function Heading () { return 

Title

; }

This method is probably most similar to traditional CSS: First a style is defined and then applied to the elements to be designed in this way. She is supported by Treat, Emotion, Goober, Fela, JSS, Stitches, TypeStyle and Styled JSX.

The -Variant

Another popular gait is the -Variant. It was first introduced in the Styled Components Library. Instead of defining the styles separately, this approach defines the element and associated styling together. The Styled Components API then returns a new component that already has the desired styling. It is supported by Stitches, Emotion, Styled Components and Compiled.

The CSS Property method

A newer approach, popularized by a library called Emotion, works by assigning styles to special properties. However, the API can only be used with JSX. This approach has the advantage that there is no need to import an API; styles can simply be passed on to the CSS property, similar to the use of inline styles. Because the .css property is not a standard HTML attribute, it is necessary to install a separate plug-in provided by the respective library.

2 methods to deliver the styles in the browser

There are two ways in which the styles are delivered in the browser become.

DOM injection at runtime

Most CSS-in-JS libraries add the styles to the DOM at runtime. You use either

However, the handling of dynamic styles in the browser with this approach is not possible without an additional runtime Library possible. The SSR styles inserted inline are also not cached and have to be sent to the browser again with each request. During rehydration, they are delivered to the browser again in the form of JS.

Static extraction of CSS files

A small number of CSS-in-JS libraries take a fundamentally different approach. Instead of the styles being inserted into the DOM, the libraries generate static .css files. In terms of performance, it is comparable to normal CSS files: The amount of code that is delivered to the browser is much smaller, additional runtime libraries or rehydration are not necessary here. Static .css files are cached in the browser by default. When you visit a webpage for the first time, the cache is empty, which means that the first-contentful paint takes longer than with the first-mentioned method. Dynamic styles are included in the bundle from the start, so the CSS that has to be loaded by the browser is potentially larger.
Most CSS libraries add the styles to the DOM. Only a few, including Treat, style9 and Linaria, support static extraction of CSS files.

Atomic CSS

Some Libraries take a third approach with Atomic CSS. He is inspired by CSS frameworks such as Tailwind or Tachyons. Instead of a CSS class that contains all properties that have been defined for a specific element, these libraries generate a CSS class for each property-value combination, which can then be reused in the entire codebase.
In theory, this approach is particularly suitable for large applications in which the classes be reused many times. The only catch: the class names have to be applied to each of the HTML elements, so the HTML file will be larger. Nevertheless, with this approach, the number of bytes that are delivered to the browser should on average be smaller than with the previously mentioned ones.

Find the right library

Anyone who has read this far will notice that the decision for the right library is anything but easy. However, answering a number of questions can help you decide on the right library:

  • Does the project use React or not? If so, developers are spoiled for choice between a wide range of CSS-in-JS libraries. For applications that use a different framework or Vanilla JS, however, a framework-agnostic library must be used.
  • Is the app very interactive and relies on client-side rendering or is it a dynamic website with SSR? In this case, it is probably smarter to extract static CSS files. This is how the application benefits from caching.
  • Whether CSS already exists that needs to be migrated also influences the choice. In this case, it is recommended to use a CSS-in-JS library that supports tagged templates. This makes the migration easier.
  • It also plays a role whether the application is to be optimized for first-time visitors or returning users. Static .css files offer the best UX for returning users, but an additional http request is required on the first visit, which temporarily blocks the rendering of the page. However, if you intend to frequently give your application a new look, you can of course leave out the caching factor when choosing.
  • Use developers: inside styles and components many times in one application, are frameworks based on Atomic Build CSS, probably the best option.
  • You might also be interested in

    Follow World Weekly News on

    Tyler Hromadka
    Tyler is working as the Author at World Weekly News. He has a love for writing and have been writing for a few years now as a free-lancer.

    Leave a Reply

    Must Read