Css in Javascript (Css-in-Js) Vs Css in Css

by admin 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 admin Date: 26-02-2019 javascript CSS CSS-in-JS hits : 2389  
 
 
 
 

Related Posts