A Look Back at CSS-in-JS After Several Years

CSS-in-JS
CSS-in-JS

Sure! Here’s a rewritten article based on the provided French content, focused on the keyword “CSS-in-JS,” along with a code example.

A Reflection on Years of CSS-in-JS

Over the past four years, I’ve transitioned from my initial love for CSS to exploring alternatives that offer solutions to the challenges I encounter daily. This article reflects on that journey, highlighting why CSS-in-JS has become my preferred approach.

Moving Away from Traditional CSS

In the early days, CSS was undoubtedly my favorite language in the web stack. I enjoyed experimenting with it, using clever hacks to achieve the desired layouts. CSS allowed me to create rounded corners with pseudo-elements, craft sprites, and modularize styles through selectors. However, as I began working on larger projects and in teams, I quickly realized that CSS had its limitations.

The Challenges of CSS

With teamwork came the inevitable chaos: one developer would modify a style, unintentionally affecting another part of the project. The global nature of CSS selectors meant that a change could cascade and break other styles. The complexity of CSS styling—determined by selectors, their order in the stylesheet, and specificity—often led to a maintenance nightmare. Each change necessitated a thorough review to ensure nothing else was disrupted.

To combat these issues, methodologies like BEM (Block Element Modifier) emerged. BEM promotes a more structured way of naming selectors, making styles easier to manage:

HTML
<div class="UserProfile">
  <img class="UserProfile-avatar" src="..." alt="User Avatar" />
  <h3 class="UserProfile-username">User Name</h3>
</div>

This approach shifts the mental model from complex instructions to a simple key-value relationship. However, the downside is that class names can become lengthy and repetitive.

The Birth of CSS Modules

The community has long sought a standard for scoped styles, which would address the issue of unwieldy names. CSS modules were introduced as a non-standard technical solution, injecting styles with unique prefixes corresponding to their scope. This approach alleviates the manual effort required to maintain namespaces, creating a more automated and reliable system.

I consider CSS modules to be the first iteration of CSS-in-JS. Following their popularity, various CSS-in-JS solutions emerged, each offering unique perspectives on managing styles in JavaScript environments.

The Benefits of CSS-in-JS

So, what has been the outcome of using CSS-in-JS over the last four to five years? Is it a misguided venture, or is it a valid approach?

In my experience, I work on a web application where I have full control over the markup. For practical reasons, I utilize inline styles in a widget and the Emotion library for the dashboard. To my satisfaction, I haven’t encountered any regressions related to style application since adopting CSS-in-JS.

Here’s an example of how I define and apply styles using CSS-in-JS (using ReScript):

HTML
// Store the style specification in a variable
module Styles = {
  open Css
  let callToAction =
    style([
      backgroundColor(BeOpTheme.mainGreen->hex),
      fontSize(16->px),
      padding4(~left=40->px, ~right=40->px, ~top=13->px, ~bottom=16->px),
      borderRadius(26->px),
      color("fff"->hex),
      textAlign(center),
    ])
}

// Apply the styles to the desired element
<TouchableOpacity onPress>
  <div className=Styles.callToAction>
    Click Me!
  </div>
</TouchableOpacity>

This method allows the machine to generate a hashed class name from the styles, ensuring that no unintended side effects occur elsewhere in the application. It simplifies style management, enabling me to focus on other aspects of development.

The Drawbacks of Traditional CSS

Reflecting on my earlier reliance on CSS selectors, I now realize how much complexity I accepted as the only option. Styling elements required navigating a moving map of selectors dependent on a resolution algorithm, often leading to mental fatigue.

The challenges posed by complex CSS selectors are unnecessary, making CSS-in-JS a compelling alternative. The balance of benefits versus risks leans heavily in favor of readability and maintainability when comparing JavaScript to CSS.

Common Misconceptions About CSS-in-JS

A frequent argument against CSS-in-JS is that it “breaks the web.” However, this notion doesn’t hold up in practice. The blog you’re reading is a web application utilizing CSS-in-JS. It remains fully functional, even with styles disabled or when JavaScript is turned off. The browser is fully capable of interpreting the received code.

Given that the majority of code written for browsers undergoes a compilation stage (whether through preprocessors, minifiers, etc.), why not view the web platform as a “compilation target”? Embracing abstractions allows us to work more efficiently while achieving equal or better results.

Embracing Change in Development Practices

It’s natural to resist the idea that our hard-earned knowledge might become obsolete, especially when our past experiences have shaped our understanding of development. While techniques from my early days may no longer apply, they contributed to my current perspective, enriching our community with diverse viewpoints.

However, in the rapidly evolving tech landscape, it’s crucial to archive our knowledge and accept that our understanding must adapt. Tomorrow’s innovations will redefine what is possible, and our collective experience will drive progress.

Looking Ahead

As we move forward, I hope web standards groups focus on the problems outlined here. Instead of introducing new selectors or layout systems that offer little beyond existing capabilities, let’s invest energy into making the web platform more accessible and maintainable.

We should aim for solutions that ease common challenges—such as managing focus traps in modals or adapting CSS properties based on available space—rather than merely scratching the surface.

In conclusion, CSS-in-JS represents a transformative shift in how we approach styling in web development. By embracing this paradigm, we can create more robust, maintainable, and enjoyable coding experiences.

This version includes the main keyword “CSS-in-JS” throughout the article while ensuring that it’s SEO-friendly with headings and structured content. Let me know if you need any further modifications!