CSS in JavaScript (CSS-in-JS) Vs CSS in CSS

CSS in JavaScript (CSS-in-JS) Vs CSS in CSS
by Janeth Kent Date: 26-02-2019 javascript CSS CSS-in-JS

What actually is CSS-in-JS?

You've certainly heard or read words like CSS-in-JS, Styled Components, Radium, Aphrodite and you're and you're stuck in limbo there, "why is it?

I'm completely happy about CSS - in - CSS!"

We are here to explain these new concepts and clarify them. That said -feel free to use CSS-in-CSS -you are not required to use CSS-in-JS under any conditions. Everything that works best for you and makes you happy is always the best solution.

CSS - in - JS is a highly sensitive and controversial issue - we advocate an open mind and weigh if it makes sense for you - ask yourself, will it improve my workflow? The only thing that matters is to use tools to make you happier and more productive!

Let's take a shot at CSS- in-JS.

CSS - in - JS refers to a series of ideas to help solve CSS problems. As this is not a specific library, different libraries can solve different problems and use different strategies, depending on the nature of their implementation.

But even so, all implementations have in common that they approach things using APIs instead of the convention, and use JavaScript as a language for styles authoring.

Modules vs NO modules

According to the repo, CSS modules are:

CSS files in which all class names and animation names are scoped locally by default.

CSS has never had actual modules, and nor did JavaScript. Then, web applications prerequisites really have evolved and JavaScript has added a module system.

First in the form of a bolt - on solution (CommonJS), then as a standard, statically easily interpretable module system known as ECMAScript Modules (ESM).

The logic behind the modules pertains to both JavaScript and CSS: to hide implementation details by exposing only public APIs. We must be able to disconnect subsystems of an application in order to make changing code more predictable.

However, not every application deserves this, it makes it much easier to maintain medium-sized and large applications and to configure and remove internal implementation details. Problems appear with more complexity, the smaller the application the less complex it usually contains.

We all know that CSS always has a single global namespace, for instance, a class can be added to any element, a tag selector should be used for targeting any element in our document. Initially, CSS was created to style documents and components were not required.

The whole page was specifically styled as a huge chunk and usually, not many people worked on it. Since then, however, the complexity of many websites has increased massively and this is the primary reason for the creation of many CSS methodologies.

When many people contribute to a project over the years, none of the conventions is easy to establish and consistently implement.

Current websites are complicated enough to require many front-end developers working in different areas of the site. These parts are reused throughout the global site in various ways that require these blocks to be fully interactive and functional.

The consequence in normal CSS is the lack of coherence in the organization of a project's style and styles that behave in an unpredictable way.

With CSS Modules, it’s a guarantee that all the styles for a single component:

  1. Live in one place
  2. Only apply to that component and nothing else

As Hugo Giraudel said in his tutorial on the subject:

[the classes] are dynamically generated, unique, and mapped to the correct styles.

CSS-in-JS automates the scoping by generating unique selectors.

This is a simplified example of how a selector is generated by CSS - in - JS libraries:

const css = styleBlock => {
  const className = someHash(styleBlock);
  const styleEl = document.createElement('style');
  styleEl.textContent = `
    .${className} {
      ${styleBlock}
    }
  `;
  document.head.appendChild(styleEl);
  return className;
};
const className = css(`
  color: red;
  padding: 20px;
`); // 'c23j4'

About dependencies

CSS offers reuse of a rule level code, which means that a style block is reused, a rule has a selector. If the selector applies to an element, the whole style block applies. This is basically possible in two ways:

1. A CSS rule contains multiple selectors for various HTML elements.

2. Multiple class names or other attributes are applied to HTML elements, resulting in multiple CSS rules targeting them.

Obviously, neither of those performs perfectly, because both lead to monolithic code structure, where everything depends on everything. It becomes hard to clearly isolate the subsystems.

In the first case, the rule obtains references to other subsystems when we add many selectors to a single CSS rule. You can't change those subsystems without touching that rule and it's easy to forget.

In the second case, if we use multiple names of classes or other attributes, multiple CSS rules target the element. This tends to make the relationship complicated again and what needs to be removed is easily forgotten again.

In both cases, without a good strict system, we create dependencies that are difficult to understand and change over time.

CSS - in - JS actually makes dependencies explicit, as variables always visually refer to the code value. They can be traced because we can examine where the value comes from. They are robust because CSS values, properties or whole style blocks can be reused as we see fit.

The problem of the Dead Code

It is generally difficult to track unused CSS rules and inform the author or remove them from the bundle due to the implicit relationship between HTML and CSS. You ca n't often know where the rules were used.

For example, multiple code bases or class names could be applied conditionally from a language used to generate HTML or JavaScript on the client side.

Dead code can have a highly negative impact on the performance of the site and developers ' ability to understand the code.

Thanks to explicit, traceable variables and modules in JavaScript, we can implement solutions on top, which create an explicit connection between a CSS rule and the HTML element.

CSS-in-JS helps with removing dead code.

Specificity of non - deterministic order of source

If you create a one-page application and divide the CSS bundle by page, you can probably end up with a non - deterministic specification of the source order. The order in which CSS is injected in such situations depends on user actions, which causes selectors to apply chaotically to the HTML elements.

Imagine loading "namefile" and switching to "namefile2" without a complete reload of the document. You loaded CSS - "namefile" and then "namefile2" CSS. If selectors used in the CSS - "namefile2" should override CSS - "namefile" selectors, we are good because CSS for namefile2 was later loaded and has a higher specification of the source order.

To fix this, CSS and HTML can be coupled firmly, so we always know what CSS is used by the HTML currently rendered.

CSS-in-JS helps to avoid non-deterministic source order specificity.

Omnipotent selectors

It is weird because some people think that CSS is too powerful and some others refer to CSS-in-JS as too powerful regarding a level of abstraction.

The truth is that they are both powerful and effective but in different sectors. CSS selectors are too powerful mostly because any element in the document can be targeted. It's a major issue because we try to write to CSS that only has access to elements in our HTML block or component.

By scoping its selectors, CSS-in-JS helps to restrict this power. It is still not a permanent solution, but if a given library supports cascading, these selectors can reach any child element. Although writing a more restricted CSS by default is a good leap forward.

However most CSS - in - JS libs support cascading, but it is not because it is safe, but because it is practical and security mechanisms do not yet have good alternatives.
Shadow root CSS is still not where it needs to be for mass adoption.

On the other hand, we have JavaScript with its more expressive syntax, which allows many more patterns and notes.

Advanced UX logic without conditionals, functions, and variables is is often hard to express. A pure declarative syntax actually works well if the runtime is highly specialized for the case, while CSS performs a wide range of tasks.

What are the Pros and cons of using CSS-in-JS

Pros:

  • Thinking in components — CSS-in-JS abstracts the CSS model to the component level, rather than the document level (modularity).
  • CSS-in-JS leverages the full power of the JavaScript ecosystem to enhance CSS.
  • Scoped selectors — CSS has just one global namespace. JSS generates unique class names by default when it compiles JSON representation to CSS.
  • Vendor Prefixing —The CSS rules are automatically vendor prefixed, so you don’t have to think about it.
  • Code sharing — Easily share constants and functions between JS and CSS.
  • Only the styles which are currently in use on your screen are also in the DOM .
  • Dead code elimination

Cons:

  • Learning curve.
  • New dependencies.
  • Harder for newer teammates to adapt to the code-base. People who are new to front-end have to learn “more” things.
  • Challenging the status quo. (not necessarily a con)

Conclusions

We hope that we have been able to give you an idea of the key factors of the concept. We do not intend to evaluate any technology or provide a complete list of features that vary from one implementation to another.

Furthermore, we don't say that CSS - in - JS is the only future we can have, but if the community doesn't understand the problems that these tools are trying to solve, how will we move forward?

 

 

Background vector created by freepik - www.freepik.com

 
by Janeth Kent Date: 26-02-2019 javascript CSS CSS-in-JS hits : 11166  
 
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN AND DEVELOPMENT.

 
 
 

Related Posts

How to upload files to the server using JavaScript

In this tutorial we are going to see how you can upload files to a server using Node.js using JavaScript, which is very common. For example, you might want to…

How to combine multiple objects in JavaScript

In JavaScript you can merge multiple objects in a variety of ways. The most commonly used methods are the spread operator ... and the Object.assign() function.   How to copy objects with…

The Payment Request API: Revolutionizing Online Payments (Part 2)

In the first part of this series, we explored the fundamentals of the Payment Request API and how it simplifies the payment experience. Now, let's delve deeper into advanced features…

The Payment Request API: Revolutionizing Online Payments (Part 1)

The Payment Request API has emerged as the new standard for online payments, transforming the way transactions are conducted on the internet. In this two-part series, we will delve into…

Let's create a Color Picker from scratch with HTML5 Canvas, Javascript and CSS3

HTML5 Canvas is a technology that allows developers to generate real-time graphics and animations using JavaScript. It provides a blank canvas on which graphical elements, such as lines, shapes, images…

How do you stop JavaScript execution for a while: sleep()

A sleep()function is a function that allows you to stop the execution of code for a certain amount of time. Using a function similar to this can be interesting for…

Mastering array sorting in JavaScript: a guide to the sort() function

In this article, I will explain the usage and potential of the sort() function in JavaScript.   What does the sort() function do?   The sort() function allows you to sort the elements of…

Infinite scrolling with native JavaScript using the Fetch API

I have long wanted to talk about how infinite scroll functionality can be implemented in a list of items that might be on any Web page. Infinite scroll is a technique…

Sorting elements with SortableJS and storing them in localStorage

SortableJS is a JavaScript extension that you will be able to use in your developments to offer your users the possibility to drag and drop elements in order to change…

What is a JWT token and how does it work?

JWT tokens are a standard used to create application access tokens, enabling user authentication in web applications. Specifically, it follows the RFC 7519 standard. What is a JWT token A JWT token…

Template Literals in JavaScript

Template literals, also known as template literals, appeared in JavaScript in its ES6 version, providing a new method of declaring strings using inverted quotes, offering several new and improved possibilities. About…

How to use the endsWith method in JavaScript

In this short tutorial, we are going to see what the endsWith method, introduced in JavaScript ES6, is and how it is used with strings in JavaScript. The endsWith method is…

Clicky