Menu Search
Jump to the content X X
Smashing Conf Barcelona

You know, we use ad-blockers as well. We gotta keep those servers running though. Did you know that we publish useful books and run friendly conferences — crafted for pros like yourself? E.g. our upcoming SmashingConf Barcelona, dedicated to smart front-end techniques and design patterns.

Finally, CSS In JS! Meet CSSX

JavaScript is a wonderful language. It’s rich, it’s dynamic, and it’s so tightly coupled to the web nowadays. The concept of writing everything in JavaScript doesn’t sound so crazy anymore. First, we started writing our back end in JavaScript, and then Facebook introduced JSX1, in which we mix HTML markup with JavaScript. Why not do the same for CSS in JS?

Imagine a web component2 distributed as a single .js file and containing everything — markup, logic and styles. We would still have our basic style sheets3, but the dynamic CSS would be a part of JavaScript. Now this is possible, and one way to achieve it is with CSSX4. CSSX is a project that swallowed my spare time for a month. It was challenging and interesting, and it definitely pushed me to learn a lot of new stuff. The result is a set of tools that allows you to write vanilla CSS in JavaScript.

Further Reading on SmashingMag: Link

Similar to JSX, CSSX offers encapsulation. Being able to see all parts of a single component is a big step forward. The separation of concerns9 defined development for years, but the web is changing. Very often, we’ll work entirely in the browser, and Facebook’s approach with JSX makes a lot of sense. Understanding what is going on is easier when everything is in one place. We bind parts of JavaScript to parts of HTML anyway. By mixing both together, we’re just making these bindings explicit. If it works for HTML, it would definitely work for CSS.

CSS In JS – The Concept Link

My thinking around putting CSS in JavaScript dates back to 2013, when I created a library10 that started as a CSS preprocessor but that I converted to a client-side tool. The idea was simple: Convert object literals to valid CSS, which is later applied to the page. The styles “travel” with the JavaScript. They are bundled together, and you don’t have to manage external style sheets. While I was experimenting with this approach, I identified two issues:

  • Flash of unstyled text (FOUT) was the first problem. If we rely on JavaScript to deliver the CSS, then the user will see unstyled content for a second (or more) before getting the styled page. This results in layout shifts and leads to a bad user experience.
  • The second problem is that there is no style sheet. There are plenty of examples of styles being applied with JavaScript, but most of them are inline styles. In other words, they modify the style property of the DOM element. That’s fine, but we can’t go through all of the elements that need styling and change their attributes. Also, not everything can be placed in a style attribute — media queries and pseudo-classes, for example.

My goal was to solve these two problems, and I started shaping a solution. The following image illustrates how I imagined working with CSS in JavaScript:

css in js11

(View large version12)

There would be a library that stands between your code and the actual styles applied to the page. Its responsibility would be to create a virtual style sheet, and it would associate a <style> tag with it. Then, it would provide an API for managing CSS rules. Every interaction with your JavaScript style sheet would be mirrored to the injected <style> tag. With this approach, you would keep the dynamic styles tightly coupled to the JavaScript that controls it. You wouldn’t have to define new CSS classes because you would generate the CSS rules on the fly at runtime.

I prefer to generate and inject CSS because inline styling doesn’t scale. It’s technically easy, but it simply doesn’t scale. If there is CSS in JavaScript, we should be able to control it like a real style sheet. We should be able to define styles and then add, remove or update them inside. And those changes should be applied to the page just like the style sheet in a static file.

The FOUT problem is a matter of trade-offs. The question is not, “Should we put our CSS in JavaScript,” but rather, “What part of the CSS could be written in JavaScript?” Certainly the typography, the grid, the colors should all be in a static file so that browsers can consume it as quickly as possible. However, a ton of stuff is not needed immediately — for example, classes relating to state, like is-clicked and is-activated. In the world of single-page apps, everything generated by JavaScript can be styled with JavaScript. That’s because it does not appear before we have the whole JavaScript bundle. In a large-scale application, forming different blocks and keeping them separated is really important. The fewer the dependencies a single component has, the better. HTML and CSS are hard dependencies of our client-side JavaScript13 views. Without them, we can’t really display content. Grouping them in one place would reduce the complexity of our projects.

Based on these conclusions, I started writing the CSSX client-side library.

Meet The CSSX Library Link

To make the CSSX library14 available, either include the cssx.min.js15 file on your page or install the npm module by running npm install cssx. If you have a build process, then you’ll probably be interested in the npm package.

An online demo is available on GitHub16. You can see CSSX in action there.

(The CSSX client-side library is needed so that the CSSX is injected at runtime. Later, we will see what other modules are required to support the vanilla CSS syntax. Till then, let’s focus on the JavaScript-only API.)

Here is a very basic example of one style sheet with one rule registered in it:

var sheet = cssx();
sheet.add('p > a', {
  'font-size': '20px'

If we ran this in a browser, we’d see a new style tag injected in the head of the document:

<style id="_cssx1" type="text/css">p > a{font-size:20px;}</style>

The add method accepts a selector and CSS properties as an object literal. This works, but it’s a static declaration. There would be almost no benefit to doing this in JavaScript. We could just as easily place these styles in our external CSS file. Let’s transform the code to the following:

var sheet = cssx();
var rule = sheet.add('p > a');
var setFontSize = function (size) {
  return { 'font-size': size + 'px' };


Now there’s another thing. We are now able to change the font size dynamically. The result of the code above is this:

p > a {
  font-size: 24px;

So, writing CSS in JavaScript now becomes a composition of object literals. We may use all of the features of the JavaScript language to build them. Simple things like defining a variable, using factory functions and extending base classes are here by default. Encapsulation, reusability, modularity — we get all of these things for free.

The CSSX library has a minimalist API, mainly because JavaScript is really flexible. The composition of the CSS is left to the developer. The exposed functions revolve around the production of actual styles. For example, while writing CSS, we tend to create groups. Some of these groups are formed by the structure of the layout — styles for the header, the sidebar and the footer. Here is how to scope the styles using a CSSX rule object:

var sheet = cssx();

// `header` is a CSSX rule object
var header = sheet.add('.header');

header.descendant('nav', { margin: '10px' });
header.descendant('nav a', { float: 'left' });
header.descendant('.hero', { 'font-size': '3em' });

The result of this snippet is this:

.header nav {
  margin: 10px;
.header nav a {
  float: left;
.header .hero {
  font-size: 3em;

Instead of header.descendant, we may use header.d. It would be annoying to have to write descendant all of the time; so, a .d shortcut exists.

We have another method similar to descendantnested. Instead of chaining the selectors, the library would nest the definitions. Here is an example:

var smallScreen = sheet.add('@media all and (max-width: 320px)');
smallScreen.nested('body', { 'font-size': '10px' });

/* results in
@media all and (max-width: 320px) {
  body {
    font-size: 10px;

This API may be used to create media queries or @keyframes definitions. In theory, this is enough to produce a Sass-like output. There is also the .n shortcut, instead of .nested.

So far, we’ve seen how to produce valid CSS that gets applied to the page at runtime. However, writing styles like that takes a lot of time, and even though our code has a good structure, it’s not as nice as writing vanilla CSS.

The Challenging Part: Actual CSS Syntax In JavaScript Link

As we’ve seen, writing CSS in the format shown above is not really nice, mainly because we have to wrap almost everything in quotation marks. We can do some optimization, like using camel casing, creating helpers for the different units and so on, but it’s still not as clean and simple as regular CSS. Placing vanilla CSS in JavaScript leads to the well-known unexpected token error, because the JavaScript engine is not designed to accept code in such a format. OK, then, how do we introduce the syntax we want? JSX created it, right? Well, it didn’t. We don’t have actual HTML tags working in JavaScript. What’s happening is that we translate (or, more accurately, transpile) JSX to valid JavaScript at buildtime. The final bundle that is executed in the browser contains valid code. Here is an example:


(View large version18)

Of course, this comes at a cost: one more step in our build process, more configuration and more things to think about. But, to be honest, I’m ready to trade that for better code organization and scalability. JSX simply makes our life better by hiding the complexity of managing HTML templates.

And JSX was exactly what I wanted, but for CSS. I started digging into Babel19, because that’s the official transpiler of JSX at the moment. It uses the Babylon20 module to parse the source code and transform it to an abstract syntax tree21 (AST). Later, the babel-generator22 parses that tree and turns it into valid JavaScript code. That’s how Babel understands JSX. It uses same approach for the ES6 features that are still not supported by all the browsers.

Babel transpiler23

(View large version24)

So, all I had to do is see how Babylon understands JSX and do the same for CSS. The module is written like so, so it allows extension from the outside. In fact, almost anything can be changed. JSX is a plugin there, and I was keen to create one for CSSX.

I knew about AST and how helpful it can be, but I never spent time learning how to generate one. It is basically a process of reading small chunks (or tokens) of the code, one by one. We have a bunch of assertions trying to form a meaningful sequence of tokens. If something is recognized, then we define a context and continue parsing until we exit the current context and continue with another one. Of course, there are many edge cases that have to be covered. And the fun part is that we can’t extend the parser until we know every little detail about it. It took me a couple of weeks to read and really understand what is going on there.

In the beginning, I made the mistake of following the JSX plugin’s implementation. I can’t tell you how many times I started the CSSX plugin. Every time, I ended up with something that either didn’t fully cover the CSS syntax or broke JavaScript’s syntax. Then, I realized that JSX is quite different, and I started extending only what CSS needs. The test-driven development approach worked perfectly here. I should mention that Babylon has more then 2100 tests. And that’s absolutely reasonable considering that the module understands such a rich and dynamic language like JavaScript.

I had to make a couple of interesting design decisions. First, I tried parsing code like this:

var styles = {
  margin: 0,
  padding: 0

Everything was going fine until I decided to run my plugin against all of the tests in Babylon. The parser usually produces an ObjectExpression node from this code, but I was doing something else because I recognized this as CSSX. I effectively broke the JavaScript language. There is no way to find out what we have until we parse the whole block. That’s why I decided to use another syntax:

var styles = cssx({
  margin: 0;
  padding: 0;

We are explicitly saying here that we are writing a CSSX expression. Tweaking the parser is much easier when we have a clear entry point. JSX does not have this problem because HTML is not even close to JavaScript, and there are no such conflicts.

I was using CSSX with the cssx( … ) notation for a while, but then I realized that I could replace it with <style> … </style>. It was a cheap switch. Every time the code lands in the parser, just before processing it, we run a simple regex replacement25:

code = code.replace(/<style>/g, 'cssx(').replace(/<\/style>/g, ')');

This helps us write the following:

var styles = <style>{
  margin: 0;
  padding: 0;

And we have the same result in the end.

Start Writing Vanilla CSS In JavaScript Link

Let’s say we have a tool that understands CSSX and produces proper AST. The next step is to get a transpiler that generates valid JavaScript. The package that deals with that is CSSX-Transpiler26. Under the hood, we are still using babel-generator, but only after we substitute our custom CSSX nodes with something that Babel understands. Another helpful module is babel-types27. There are a ton of utility functions, and without them, generating a tree for the generator would be really difficult.

Types of CSSX Expressions Link

Let’s see a couple of simple transformations.

var styles = <style>{
  font-size: 20px;
  padding: 0;

This is transformed to the following:

var styles = (function () {
  var _2 = {};
  _2['padding'] = '0';
  _2['font-size'] = '20px';
  return _2;

That’s the first type, where we produce a simple object literal. The equivalent of the code above is this:

var styles = {
  'font-size': '20px',
  'padding': '0'

If you scroll up, you will see that that’s exactly what we need in the CSSX client-side library. If we operated with a lot of those, then it would be nice to use vanilla CSS.

The second expression contains more information. It bundles the whole CSS rule — selector and properties:

var sheet = <style>
  .header > nav {
    font-size: 20px;
    padding: 0;

Here is the transpiled JavaScript:

var sheet = (function () {
  var _2 = {};
  _2['padding'] = '0';
  _2['font-size'] = '20px';

  var _1 = cssx('_1');

  _1.add('.header > nav', _2);

  return _1;

Note that we are defining a new style sheet — cssx('_1') — I should clarify that if we run this code twice, we won’t be creating an additional <style> tag. We’d be using the same one because cssx() receives the same ID (_1) and returns the same style sheet object.

If we added more CSS rules, we’d see more _1.add() lines.

Going Dynamic Link

As mentioned, the main benefit of writing CSS in JavaScript is to gain access to wider range of tools, such as defining a function that gets a number and outputs a font-size rule. I had hard time deciding on the syntax for these “dynamic parts.” In JSX, this is solved easily by wrapping code in braces. Again, doing the same in CSSX would be difficult because braces conflict with other stuff. We always use them when defining CSS rules. So, I initially decided to replace them with the grave accent (or the backtick):

var size = 20;
var styles = <style>
  .header > nav {
    font-size: `size + 2`px;
    padding: 0;

The result would be this:

.header > nav {
  padding: 0;
  font-size: 22px;

We can use dynamic parts everywhere. Whatever we place inside is considered valid JavaScript and is executed.

var size = 20;
var prop = 'size';
var selector = 'header';
var styles = <style>
  .`selector` > nav {
    font-`prop`: `size + 2`px;
    padding: 0;

Similar to JSX, the code is transformed to valid JavaScript:

var size = 20;
var prop = 'size';
var selector = 'header';
var styles = (function () {
  var _2 = {};
  _2['padding'] = '0';
  _2["font-" + prop] = size + 2 + "px";

  var _1 = cssx('_1');

  _1.add("." + selector + " > nav", _2);

  return _1;

I should mention that the self-invoking function around the transpiled code is needed to keep the right scope. The code we place inside the so-called dynamic expressions should use the right context. Otherwise, we’d probably be requesting access to undefined variables or would be reading from the global scope. The other reason to use a closure is to avoid collisions with other parts of our application.

After getting some feedback, I decided to support two other syntaxes for those dynamic expressions. Some solid refactoring was needed for the code that defines words inside CSSX. Now, it is possible to use {{ … }} or <% … %>:

var size = 20;
var styles = <style>
  .header > nav {
    font-size: px;
    padding: 0;

“Show Me The Code!” Link

Let’s build something real and see how CSSX works in practice. And because CSSX is inspired by JSX, we’ll create a simple React28 navigation menu. The result will look like this:

React CSSX example

(The final source code of this example is available on GitHub29. Simply download the files, and install the dependencies with npm install. Then, run npm run dev to compile the JavaScript, and open example/index.html in a browser. A live demo30 of the result is also available.)

The Base Link

We’ve already established that CSSX is not meant to serve all of the CSS. It should contain only those bits that are dynamic. The basic CSS in this example would be as follows:

body {
  font-family: Helvetica, Tahoma;
  font-size: 18px;
ul {
  list-style: none;
  max-width: 200px;
ul, li {
  margin: 0;
  padding: 0;
li {
  margin-bottom: 4px;

Our navigation will be made up of an unordered list of items. Every item will contain an <a> tag, which represents the clickable area.

The Navigation Component Link

(Don’t worry if you are not familiar with React. The same code can be applied in other frameworks. What is important here is how we use CSSX to style the buttons and define their behavior.)

The first thing we have to do is render links on the page. Let’s say that the items in the list will come to the component as an items property. We’ll loop through them and create <li> tags.

class Navigation extends React.Component {
  constructor(props) {
    this.state = { color: '#2276BF' };
  componentWillMount() {
    // Create our style sheet here
  render() {
    return <ul>{ this._getItems() }</ul>;
  _getItems() {
    return, i) => {
      return (
        <li key={ i }>
          <a className='btn' onClick={ this._handleClick.bind(this, i) }>
            { item }
  _handleClick(index) {
    // Handle link's click here

We’ve put a color variable in the component’s state and will use it later in our style sheet. Because the styles will be generated at runtime, we may go even further by writing a function that returns the color. Note that, by placing the CSS in the JavaScript, we are no longer living in the static, declarative land of CSS!

As it is, the component is ready for rendering.

const ITEMS = [

  <Navigation items={ ITEMS } />,

The browser simply displays our ITEMS on the screen. Within the static CSS, we’ve removed the default bullets of the unordered list and cleared the space around the items. The result is this:

React CSSX example

Now, let’s add some CSSX and define the initial look of the items. A good place to do this is the componentWillMount function because it’s the method that is fired before the component gets on the page.

componentWillMount() {
  var color = this.state.color;
    li {
      padding-left: 0;
      (w)transition: padding-left 300ms ease;
    .btn {
      display: block;
      cursor: pointer;
      padding: 0.6em 1em;
      border-bottom: solid 2px `color`;
      border-radius: 6px;        
      background-color: `shadeColor(color, 0.5)`;
      (w)transition: background-color 400ms ease;
    .btn:hover {
      background-color: `shadeColor(color, 0.2)`;

Notice how we’ve used CSSX expressions to define the bottom border’s color and the background color. shadeColor is a helper function that accepts a color in HEX format and shades it based on the second parameter (which is between -1 and 1). That’s not really important right now. The result of this code is a new style sheet injected in the head of the page. The CSS there is exactly what we need:

li {
  padding-left: 0;
  transition: padding-left 300ms ease;
  -webkit-transition: padding-left 300ms ease;
.btn {
  background-color: #91bbdf;
  border-radius: 6px;
  border-bottom: solid 2px #2276BF;
  padding: 0.6em 1em;
  cursor: pointer;
  display: block;
  transition: background-color 400ms ease;
  -webkit-transition: background-color 400ms ease;
.btn:hover {
  background-color: #4e91cc;

The (w) in front of the properties generates a prefixed version.

Now, our navigation is not simple text anymore:

React CSSX example

React CSSX example.

The last bit of our component is the interaction with the user. If we click on some of the links, they should shrink from the left and a static background color should be set. In the _handleClick function, we’ll receive the index of the clicked item; so, we can use nth-child CSS selector to style the correct button:

_handleClick(index) {
    li:nth-child({{ index + 1 }}) {
      padding-left: 2em;
    li:nth-child({{ index + 1 }}) .btn {
      background-color: {{ this.state.color }};

This works but there is one problem. An item that has been clicked is not restored to its initial state if we click on another link. After two clicks, for example, our document might contain the following:

li:nth-child(4) {
  padding-left: 2em;
li:nth-child(4) .btn {
  background-color: #2276BF;
li:nth-child(3) {
  padding-left: 2em;
li:nth-child(3) .btn {
  background-color: #2276BF;

So, we have to clear the style sheet before styling the clicked item.

var stylesheet, row;

// creating a new style sheet
stylesheet = cssx('selected');

// clearing all the styles

// adding the styles
  li:nth-child({{ index + 1 }}) {
    padding-left: 2em;
  li:nth-child({{ index + 1 }}) .btn {
    background-color: {{ this.state.color }};

Or, if we go with method chaining, we’d have this:

      li:nth-child({{ index + 1 }}) {
        padding-left: 2em;
      li:nth-child({{ index + 1 }}) .btn {
        background-color: {{ this.state.color }};

Notice that we’ve specified an ID of the style sheet: selected. This is important; otherwise, we’d get a different style sheet every time.

With the change above, our example works exactly as the animated GIF at the beginning of this section.

Even with such a simple example, we can recognize some of CSSX’s benefits:

  • We don’t have to deal with additional CSS classes.
  • There is no interaction with the DOM because we don’t have to add or remove CSS classes.
  • We have real dynamic CSS, tightly coupled with the logic of the component.

Summary Link

HTML and CSS in JavaScript might seem strange, but the truth is that we have been doing it for years. We precompile our templates and place them in JavaScript. We form HTML as strings, and we use inline styling produced by JavaScript. So, why not use the same syntax directly?

In the last year, I’ve used React31 heavily, and I can say that JSX is not bad at all. In fact, it improves maintainability and shortens the time spent getting into a new project.

I’m still experimenting with CSSX. I do see similarities with JSX in the workflow and result. If you want to see how it works, check out the demo32.

Language Link

Packages Link

Examples Link

(rb, ml, al, il)

Footnotes Link

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44

↑ Back to top Tweet itShare on Facebook

Krasimir Tsonev is a coder with over ten years of experience in web development. Author of two books about Node.js. He works as a senior front-end developer for a startup that helps people reaching clinical trials. Krasimir is interested in delivering cutting edge applications. He enjoys working in the industry and has a passion for creating and discovering new and effective digital experiences.

  1. 1


    • 2

      JSX, CSSX, React and npm are all terrible ideas. What a bloated, slow, insecure mess. Front end web development is going to shit.

      • 3

        I agree, keep CSS out of JS. What ever happened to separation of concerns? Should we mix and match Java and C++ code too?

        • 4

          About separation of concerns.
          Does having css and html in separate files means separation of concerns?
          If you have in your css

          .names li > a {
          color: green;

          What is “.names li > a”?
          Isn’t that html in your css?
          If you decide to change your html to add a wrapper “div” around your “a” tag, will that break your css?
          Why is it ok to have html in css and not css in js?
          And of course that I am using separate css files. I just think that using small components in building UI is not some new popular trend for no reason. My code is really easier to maintain with small isolated components.
          I am sure that cssx is not ready for use, but it is a step in challenging existing approaches. And constantly questioning things is the force moving us forward.

          • 5

            Not even junior devs would write selectors like that. People use classnames and avoid html selectors altogether. This is the next thing you learn after css 101. Hope this terrible idea of putting css to js dies

      • 6

        Juan Muillez

        April 21, 2016 3:52 pm

        CSSX? Trash. This was somebody’s hobby project and it was probably fun to create, but it’s another case where just because you could do it doesn’t necessarily mean you should do it.

        Your other jabs? Well, there’s a little hugbox over here for you on to cry it out with fellow forgettables of the webdev world. “I don’t wanna have to learn to stay relevant! :'(“

  2. 7

    Pretty interesting read about your process, I guess from the fact it uses the syntax, means its not really interchangeable with traditional javascript?

  3. 9

    Isn’t this making our components too big?
    Personally I like the idea of and placing a separate CSS file in the same folder as the component.
    (header/Header.js, header/Header.css)
    Why would you choose this approach over for e.g. CSS-Modules?

    • 10

      Krasimir Tsonev

      April 18, 2016 4:25 pm

      CSS-modules are pretty close to what I was searching for. CSSX is about styling dynamic bits. I.e. you don’t have to put the typographic styles or basic layout styles in there. It’s about applying styles that depend on application state.

      • 11

        Joe Zimmerman

        April 18, 2016 8:56 pm

        There’s no reason you can’t put the dynamic bits into CSS Modules though. If you just create a class that is only used in certain states, then you can apply that class dynamically. Or you can use data attributes to hold state and adjust the data attribute values dynamically.

        I see this as a nice alternative to the potentially ugly style syntax that several libraries have enabled, but you lose the composition from CSS Modules sadly.

        • 12

          Krasimir Tsonev

          April 19, 2016 5:38 am

          Well, there is a way to compose with CSSX but I didn’t document it :( I’ll think more about that and will try making it easier. Thanks.

  4. 13

    Vinicius T. Dallacqua

    April 18, 2016 9:59 am

    Nice one!

  5. 14

    Great work. I’ve been getting into react with jsx recently and can definitely see the use of your cssx.

    I noticed that you cleared out all styles and rewrote them into the generated stylesheet. Does this do a comparison and then update the stylesheet, like React does with a virtual DOM?

    • 15

      Krasimir Tsonev

      April 18, 2016 11:31 am

      I’m not quite sure what you mean by “cleared out all styles”. If we write CSSX tag similar to JSX we transform it to valid JavaScript which is later converted to pure CSS. That CSS is injected into the page. If we run the same process twice CSSX indeed compares previous and new version and does update the injected content only if there are changes.

  6. 16

    Martin Hagedoorn

    April 18, 2016 11:37 am

    After reading part of the article I am wondering.. Why do we want to create another dependency for some basic HTML and CSS? Why do we need to come up with new tools to solve a problem which is not there? For maintainability purposes? Ease of use?

    It looks like a nice experiment, but to be honest I would not think about using it like this.

    • 17

      Krasimir Tsonev

      April 18, 2016 4:29 pm

      Fare enough. I perfectly understand that CSS in JavaScript or HTML in JavaScript is not for every project. I see some benefits in my personal use case.

    • 18

      Nick Scheuring

      April 18, 2016 5:48 pm

      In the last project I worked on we used a lot of dynamically styled objects via JS so I definitely see use cases. To use a color picker to dynamically style cells in a grid for example. So an issue I ran into when I developed JS generated CSS on the fly was that browsers (IE) have limitations on the number of tags. So the best solution was to use a single CSS stylesheet until it ran out of space and then continue to add them until you hit the limit. The limit is pretty large (4095) so when manually adding CSS you don’t see it much, however when developing large web applications you can actually hit it pretty quickly.

      • 19

        Krasimir Tsonev

        April 19, 2016 5:42 am

        CSSX indeed adds CSS rules dynamically but it also compares if the same styles are already there. I mean it’s not just injecting everything all the time. It’s not also creating a new tag every time. In most of the cases it works with only one stylesheet and on tag.

        • 20

          Dylan Valade

          April 19, 2016 1:09 pm

          Krasimir, thanks for putting your ideas out there. You have made a good pitch for CSS in JS and now it’s clear how passionately the group feels about CSS freedom.

          One way to pivot this work into something my company would use is leveraging your techniques to determine if styles are needed by the DOM or not.

          A step forward in the build process would remove selectors that can’t exist in any production template. Scan the HTML and JS for DOM attributes and only allow those that could exist to remain in the minified CSS.

          It may already be in use but I haven’t seen it. This approach could reduce CSS bloat especially for themes and frameworks.

        • 21

          Nick Scheuring

          April 25, 2016 8:31 am

          Hi Krasimir,

          Thanks for your comment. That’s a great way to go about it. My comment was a bit unclear (because it’s about a very specific application and only a paragraph or so). The reason that I mentioned the limits was because in the use case I described there was a CSS class defined based on the color chosen, with the option to individually assign the color to cells in a grid. The grid could contain thousands of cells, and there are thousands of colors, so the case that I mentioned was in the case of applying a number of different and each intended CSS classes which would exceed the browser limitations (and silently fail as there is no error message in that case, the CSS is simply ignored). That is a great feature to check what exists and not simply inject duplicates. I was also reading other comments about cleaning up unused tags to help reduce ‘clutter’, which would possibly be helpful as well. How much of a hit does performance take by having to search through the CSS tags for duplicates? Are the files searched at every tag creation? There are so many challenges with a feature like this. Thanks for responding!


    • 22

      because someone wants reusable self contained components and component libraries, as always has been in application development, but to define them with web technologies one must use at least 2 files and 2 languages plus the server side.

  7. 23

    Jason T Featheringham

    April 18, 2016 11:54 am

    I’m truly impressed with your level of detail in this article. Unfortunately, the concept–not your belief–is rubbish. There are so many benefits to separating your content, presentation and behavior into separate files, especially including not coupling them to a specific technology stack which further “wraps” and obfuscates simple HTML and CSS. This is what things like pre-deploy scripts are for.

    • 24

      Krasimir Tsonev

      April 18, 2016 4:30 pm

      Interesting. Is that valid for JSX or that’s your opinion about CSSX?

      • 25

        JSX is a terrible idea.
        Keep HTML and JS separate.
        I thought front-end developers passed that when we all agreed that code in the same files is a bad idea, in the years of PHP and ASP.

        Why is adding HTML or CSS inside JS any better?

  8. 27

    Years ago, HTML/CSS/JS were all joined into a single HTML file. There was a major effort to separate those concerns into separate files with CSS stylesheets and Unobtrusive JavaScript.

    Both of those paradigms (moving concerns to separate files) were done for good reasons.

    What it looks like to me, with React and CSSX, is a return to the days where everything is thrown into a single file again and there isn’t clear separation of code/concerns.

    Personally, I think combining everything is a bad idea. It leads to code that is often harder to maintain and bloated files. The “look/feel (CSS)” of a component is separate from the “element (HTML)” itself, which is separate from the “interactions (JavaScript)”.

    Anyone else remember the early days of poorly-written PHP web apps that had single files with thousands of lines of code? From my view, it seems that many of the lessons professional object-oriented development has taught us over the years are being abandoned so we can write EVERYTHING in JavaScript.

    • 28

      Krasimir Tsonev

      April 18, 2016 4:34 pm

      Well, the idea of mixing markup and logic is not new and it is not typical for the React community only. There was something called mxml (by Adobe in flex development). We are not talking about placing everything in one place. Of course that no one wants to read a 500+ lines file with all the things mixed up. If the result of using JSX and CSSX is such file then the problem is in the developer not in the tools. JSX gives us modularity and componentization. It’s really about writing small one-job components. Whether CSSX is doing the same thing or not we’ll see :)

    • 29

      You are right on the money Dan. React and the clusterfuck of nonsense it brings can stay at Facebook.

      • 30

        Krasimir Tsonev

        April 19, 2016 5:45 am

        I strongly disagree with that. React has lots of benefits over the typical front-end development workflow. It is true that it is not working for every case and it shouldn’t.

        • 31

          blobby tables

          April 19, 2016 2:38 pm

          No, react doesn’t have benefits. React epitomizes the cancer of front-end development: emphasis on shiny tools over reasonability. The web is based on HTML, CSS, and JavaScript. They form a hierarchy, and are put into quantized bits called web pages. A bloated JS file which tries to take over the entire browser and essentially emulate a non-web environment is illogical and hurts both users and the web ecosystem.

  9. 32

    You said: “The separation of concerns defined development for years, but the web is changing.”

    Yes, I think we’d all agree to that :)

    That said, there’s doesn’t feel to be much of a case here for this solution. That is, this does strive to solve a new problem, but is this the best/ideal solution. Are we moving forward, or reinventing (mistakes of) the past?

    • 33

      Krasimir Tsonev

      April 18, 2016 4:36 pm

      There are 10+ modules about CSS in JavaScript. For sure that’s not for everyone and not for every project. I wouldn’t say that it’s a perfect solution but do solve some problems.

  10. 34

    Personally I think your idea is good in very certain cases, but what you try to do with it is very very bad.

    – First of all, why do you want to place everything in a single file? What about multi-thousand line heavy components? I hate searching those monsters and I really like the idea of splitting up one big and complex thing into many simple ones. Your use-case example destroys that completely and does a step backward in terms of ease of development and maintainability. W3C gave us HTTP/2 with file multiplexing for speed with many files, why throw that advantage out of the window?
    – Second there is something wrong with your CSS. You try to dynamically write lots and lots of CSS rules in your example. This is just a lot of bulk in your JS and takes away any attempt at modularity CSS gives you. You even had to clear your rules just to fix a problem with style-assignment. Why would anyone clear CSS rules? Clearing them makes debugging very hard as you don’t know what exists and what might exist under certain circumstances. Also how will you easily find the rule you are looking for in JS, when you create lots of that stuff generically? Why not write CSS classes which are reuseable? This will make it a lot easier on your whole team or other people who have to understand your code (or yourself in a few years from now). Have you ever heard about BAMIT? You should definitely check it out on Harry’s website at .
    – Third, trading “ease of use” for performance is often the right thing to do when it simplifies a real problem. But in the case of CSSX you do not solve a real problem – at least not in your examples. Your transpiled code is big and complex and it will take a multitude of time for it to run. Especially in big projects, wasting time in a script is bad. Even if your site is rendered in 90ms, users will hate you if everything they click will take 90ms because it has to run lots and lots of code to generate HTML, CSS, do checks on generated content and in the end trigger a compete re-interpret of the whole HTML and CSS by the browser.

    Those three problems might not be so apparent in very small projects and examples. Performance might be good on your development machine. But there are people with cheap, slow smartphones. Not everyone has $300 to spend on a OnePlus or (even more) on the latest iPhone. You often don’t have a good connection, hence your bulky JS will be negative for file transfer times.
    Here on SM there are articles and books about how page speed matters. As a result I cannot comprehend, why you suddenly want to trade speed for monolithic, hard-to-understand structures.

    • 35

      Krasimir Tsonev

      April 19, 2016 6:03 am

      > First of all, why do you want to place everything in a single file?
      It’s not about having large files that are difficult to read. Exactly opposite. It’s about grouping really small bits into a single place where it is easy to see the template and the logic and make the relations quickly. Does CSSX have a place in this concept – I don’t know. That’s why I’m experimenting and writing such articles. To get feedback.

      > Second there is something wrong with your CSS. You try to dynamically write lots and lots of CSS rules in your example.
      I’m not writing lots and lots of CSS rules. They are just a few rules. I agree that the basic stuff can be placed in a static file and that’s what I recommend in the CSSX documentation. CSSX should be used only for stuff that are changing. Regarding the clearing – you may not realize that but you have to do the same thing if you use plain CSS. Let’s say that you have .selected class for your navigation items and at every moment there is only one item that has this class. What you’ll probably do is to remove .selected for all the links and then apply it to the one which is clicked. It’s the same thing here. It’s just done with JavaScript and you don’t have classes.

      > Third, trading “ease of use” for performance is often the right thing to do …
      The example is showing how CSSX works. For sure you can solve the same problem by using CSS classes and maybe 10 other ways. I had a hard time picking example so I show the capabilities of CSSX. It looks like I didn’t selected the proper one. Regarding performance – CSSX has a mechanism that schedules the compilation once per frame and this is only if you change some of the stored rules. I’ll probably measure how slow it is but I wouldn’t say that it will be so bad. If it is, then no one will use React because React does compute lots of stuff on every click.

  11. 36

    James Wright

    April 18, 2016 1:52 pm

    I don’t see the benefit of this. When using React, I don’t mind placing JSX in my JavaScript code since it helps componentise my markup and highlights the flow of data, but I don’t see what CSS in my components brings to the table; are CSS files really that much of a maintenance overhead?

    Furthermore, if I were using plain old JS in a project, then I’d store my templates in HTML files and inject them into my main template at build time, but that’s just a personal preference.

    What is your use case for CSSX, and how has it proven useful to you?

    • 37

      Krasimir Tsonev

      April 19, 2016 6:17 am

      I’m still experimenting with it and I’m not using it in production. What I’m using in production is React’s inline styling. Sometimes dealing with js object literals to define styles is not nice. Especially if you have lots of styles. That was my initial idea. To allow plain js code in JavaScript.

      I see some benefits of inline styling over the add-remove-classes approach. It’s useful when the CSS values are unpredictable or wide range of numbers. There is a way to avoid duplication and architect because it’s all js at the end.

  12. 38

    This is the day when the web turned into a joke!!! JS generating CSS… wow!!! never seen it coming.

  13. 39

    Yeah! Let’s move everything to Javascript! “wonderful language”. Stop.

  14. 40

    Wow! Only 184 KB compiled code for that menu! What a great technology.
    And no non-JS fallback. What a great time to live.
    Thank you!

  15. 43

    Great work you did there. But I’d really prefer everything separated out instead of just crumbling it in 1 file. You need to provide a really strong reason why this is helpful and what problem is being solved using this. Dynamic styles have never been really a problem. We easily do that with even vanilla js.

    • 44

      Krasimir Tsonev

      April 19, 2016 6:22 am


      > We easily do that with even vanilla js.
      Well, adding and removing CSS classes is not really a scalable solution. What if I have 50+ positions of my slider. Do I have to define 50+ CSS classes. The changing of .style attribute of the DOM elements is not perfect too. We have to write one line per rule and we need an access to the actual DOM element.

      • 45

        blobby tables

        April 19, 2016 2:41 pm

        > What if I have 50+ positions of my slider. Do I have to define 50+ CSS classes

        No, you use an “…

        Do you not know HTML?

  16. 47

    While I understand the theory and intentions I still firmly believe that all of this is a short term solution in an evolving language. JSX, CSSX, it’s the equivelant of early Java web development where you embedded your JS/CSS/HTML right in with your Java code in the servlet – it was convenient, it worked, but it got out of hand and led to poor coding practices and bloated code and maintenance nightmares. Same/Similar with Ruby, PHP, ASP, and GWT. Each new language attempts to solve old problems in the same old way. It doesn’t feel like anyone is looking back on history and really attempting to forge a different path that might lead to something even better.

  17. 48

    “JavaScript is a wonderful language. It’s rich, it’s dynamic, and it’s so tightly coupled to the web nowadays.” Wonderful language? I beg to differ: JavaScript is clearly a dysfunctional programming language. And exactly in what ways is JavaScript a “rich” language? From my perspective, it’s basically an imperative/procedural language, just like Java, C#, and Python, with a smattering of functional programming (or FP) capabilities tacked on. (I won’t mention the embarrassing object prototypes feature, which is an unpopular paradigm for object-orientation.) People who say it’s rich have bought into a bill of goods.

    “First, we started writing our back end in JavaScript…” This is hardly anything to brag about. Now, this awful language has metastasized to the server side???

    “HTML and CSS in JavaScript might seem strange, but the truth is that we have been doing it for years. We precompile our templates and place them in JavaScript. We form HTML as strings, and we use inline styling produced by JavaScript.” Um, no, this way of doing things has never been commonplace. Just because you can do something stupid like this doesn’t mean that you should. It is anathema to proper software engineering. It makes software maintenance a nightmare.

    Your article is one of many that teaches developers bad habits, teaches developers to write sloppy, unmaintainable code. And encouraging people to directly program in JavaScript is to invite danger such as unnecessary software defects, increased maintenance costs, and unreliability. The best recommendation would be to use transpiled languages, instead.

    • 49

      Krasimir Tsonev

      April 19, 2016 6:28 am

      > Your article is one of many that teaches developers bad habits

      I really sorry if that’s the conclusion for you. CSSX is an experiment that makes me think lots of stuff. As we can see 90+% of the comments are negative and if some developer start using it in production without finding the right use cases then we have another problem. I doubt that there is a company that blindly use whatever new pops up.

      My goal with the article was (a) getting feedback for CSSX and (b) getting feedback around css-in-javascript idea. Even the big number of negative comments I’m still thinking that CSSX and the styling in JavaScript has its own use cases and could be used.

  18. 50

    No idea why we should mix css, html and JS so much.
    So many years we tried to separate it.
    Good presentation however will avoid to use it :)

  19. 51

    Noooooooooooooooooooooooo. Further obfuscation is inevitable, but keep your styles separate!

  20. 52

    Good article, but, why do we need to bring everything to JavaScript? Why make things complex? I see the component code and I can’t identify which language is being using, seems like another language instead JavaScript. We’re creating a lot of extra syntax polluting the main language and I really don’t see it with good eyes.

  21. 53

    Joe Swislocki

    April 18, 2016 6:09 pm

    “Finally, CSS In JavaScript! Meet CSSX”
    I feel like I’m being punk’d! Where’s Ashton Kutcher?
    Thanks for coming in today.

  22. 54

    For well over a decade, Industry Best Practices have dictated that we separate concerns. Content and presentation live in .html and .css; content and functionality live in .html and .js. Never shall we cross streams, lest the universe be torn asunder á la Ghostbusters.

    So it’s very hard for me to look at CSSX and think, “this is a good idea”. In fact, my gut response is, “I don’t like it”.

    But, after some thinking, and some heated discussions where I tried to defend the concept, I did find that my what my “gut” didn’t like was your examples.

    CSSX doesn’t need to be used with ordinary content.

    Nor should it be used when you’re trying to style some sort of binary state, e.g.: .isHidden {visibility: hidden}.

    Nor does CSSX make sense for a single value of a single property.

    But, CSSX totally seems worth it when I have many different values which can have many different properties, and those values can change in unpredictable ways that can’t be controlled with CSS. Slideshows and galleries come to mind immediately. Impress.js-ish frameworks would benefit from this in a huge way.

    Your primary example was with a navigation, and I think using navigation as your example is a bad idea, because that promotes practices that we don’t like:

    – you set baseline styles in JS, instead of a stylesheet. Why make it harder for a designer to access styles?
    – getting the index and styling with nth-child() seems like the absolute hardest way to style the thing that was clicked
    – It over complicates the role of JS; we’re talking a binary state (e.g. isClicked)

    Your navigation example presents CSSX as longer, more complex solution to a problem that we don’t even have.

    What if the example were a slideshow:

    – Each slide has varying height.
    – Each slide has a background image
    – Each slide enters view in from a different direction with different effects

    In that example, your framework is a clear a winner. It’s going to help me address styles that can’t be pushed out to a stylesheet. I don’t have a simple case of “binary states” where toggling a class will help. Heck, my animation time or my transition time might need to change based on content. I would definitely rather use your framework than anything I’d come up with.

    Great framework. Be careful with the examples. Show us how it solves problems that haven’t yet been solved and I think you’ll get more support.

    • 55

      I agree with @Paceaux, your demonstration is far too bulky. To achieve something similar in plain js takes far less time and code, example:

      I would be very interested in seeing a better use-case scenario that would prove CSSX to be more efficient to use.

    • 57

      Krasimir Tsonev

      April 19, 2016 6:32 am

      You don’t even know how right you are. I had hard time picking an example and it looks like it is not the right one. I wanted to show something simple so I focus on the CSSX but what I realize now is that simple things are not the target of CSSX.

      • 58

        I would love to see an example with either a slideshow, or some sort of impress.js-style presentation.

        If you need some inspiration, I’d put together a slideshow for a conference that I spoke at last year:

        It was a basic slideshow, but it also included some basic animations (fade ins, highlighting, etc). I spent a ridiculous amount of time creating classes that turned animations into binary states when, the reality was that I needed a framework that could easily do it for me.

  23. 59

    Nuts and Gum: together at last!

  24. 60

    Jeff Carlsen

    April 18, 2016 9:23 pm

    I would never argue that including CSS within your JS file is always the right path, but there is a valid use case for the pattern, so it’s good to see explorations of the concept.

    We’ve long talked about separation of concerns. Separating our HTML, CSS, and JS has been on way of doing that. But separating by component, and preferring small single-purpose components is another valid organizational structure.

    The ideal of this pattern would be the vast majority of your components would looking like this (I’m using SASS syntax for brevity):

    import React from "react";
    import cssx from "cssx";
    import classNames from "classnames";
    import {SPOT_COLOR, SECONDARY_CONTROL} from "./color-constants";

    const COMPONENT_CLASS = "button";
    const PRIMARY_CLASS = "primary";
    const SECONDARY_CLASS = "secondary";

    function Button(props) {
    let buttonClass = classNames(COMPONENT_CLASS, {
    [PRIMARY_CLASS]: isPrimary,
    [SECONDARY_CLASS]: isSecondary

    return {props.children};

    Button.propTypes = {
    isPrimary: React.PropTypes.bool,
    isSecondary: React.PropTypes.bool,
    children: React.PropTypes.node

    // Button Styles

    line-height: 20px;
    padding: 5px;

    &.#{PRIMARY_CLASS} {
    color: SPOT_COLOR


    export default Button;

    Everything is thus in one easy to manage file with only one set of variable references.

    • 61

      Jeff Carlsen

      April 18, 2016 9:30 pm

      Sorry for the poorly formatted code. The parser apparently choked on the JSX, and editing does not appear to be an option. Nor is preview.

  25. 62


    April 18, 2016 9:58 pm

    As if angularJS wasn’t enuf. Total wastage of browser resources. VanillaJS and vanillaCSS ftw. Some people have too much free time on their hand.. Lmao.

  26. 63

    This is terribly unnecessary. “finally” implies this is anything we should want. It isn’t. Not even close.

    This should remain one of those things that serve as a “that’s kind of cool” exercise in coding for fun, but it should not be promoted to be widely used in the wild. Here’s how it will end up being used:

    JS Obsessed Designer: “Finally” We can now have CSS in our JS! JS all the things!

    Every Other Designer on the Project: !important; !important; !important;


  27. 64

    Interesting approach, much better then inline styling, or Radium library.
    I really don’t like idea to move CSS into JS. CSS gives us a lot of awesome possibilities and looking forward to see new ones, as variables and mixins.

    I have played with CSSX and IMO this is interesting for someone who want to create simple app ASAP, and where a lot of styles depend on React state. BTW ES Lint doesn’t like CSSX syntax, so would be good to have special plugin for it.

    I still like idea of CSS Modules, which plays nice with PostCSS stuff (eg. with CSSNext plugin), but this is still quite immature if want to work with nested dependencies (and avoid :global prefix).

    I will follow CSSX, CSS Modules and maybe in future will try to use in large project. For now Sass, or PostCSS/CSSNext and Atomic styles architecture are safer solution.

  28. 65

    So nowadays it’s like… “Let’s put everything in Javascript and it’s awesome” huh?

  29. 66

    Pretty cool idea, but I’m not sure if it would be great for production though. You will know what happens if a user decides to disable JavaScript…

    • 67

      Krasimir Tsonev

      April 19, 2016 6:35 am

      CSSX is meant to be used with styles that change. The layout, typography and coloring should be statically served.

  30. 68

    Khoi Nguyen (Pro.)

    April 19, 2016 2:24 am

    I don’t think it bring a production website be awesome, at least from a performance view.

  31. 69

    Yet another way to mess up your code and piss people off. What ever happened to beautiful clean markup. KISS people! things are getting stupid with over bloated frameworks, and overthought methods.

  32. 70

    On Twitter, there is a picture which try to explain it, with less words:

  33. 71

    “I prefer to generate and inject CSS because inline styling doesn’t scale. It’s technically easy, but it simply doesn’t scale”

    What does it mean?

  34. 72

    Krasimir, I feel quite frustrated reading all those destructive comments, you put a lot of effort into this and people just don’t recognize the purpose. What I see here is, that basically it’s not about mixing and obfuscating things, it’s about (runtime) generation of styles. Why is that so bad? There are generators for almost everything, why would you ever want to generate HTML during runtime? Ah, yeah, you’re probably doing that already since a hundred years (well, almost) using PHP and other server side languages. Why wouldn’t you want to dynamically generate Style Sheets, then? You could, for example, use that engine to only emit style sheets for elements you also generated, for performance/bandwidth reasons.

  35. 73

    So you define your breakpoints not only in SASS _breakpoints , but also in your JavaScript components seperated. That’s evil.

    Each component should still have it’s own SASS with using the sass-vars and functions. To activate certain component-based styling, your component sass should start with parent of body class where the activated components are defined.

    Don’t hack and undry with this nonsense cssx.

  36. 74

    How about not putting html and css in js, but putting js and css in html.
    Oh wait …

  37. 75

    Man, this is unbelievably overcomplicated. Have you heard of Web Components specs, especially HTML Templates? You can easily add your own CSS styles inside them, using CSS, not JS. This CSSX stuff is insane.

  38. 76

    Michał Sadowski

    April 19, 2016 3:22 pm

    I don’t really understand why couldn’t you use document.styleSheets with a small helper function (mine is exactly 9 lines long) to modify rules when you need global effects and just old for when you need just a few of elements changed?

  39. 77

    CSSX could benefit from component encapsulation. See JSS’ randomly generated class names to see what I mean:

    In contrast CSSX selectors across components can conflict. Looking forward to seeing a solution for this. :]

    Also check out the JSS plugins for some inspiration, for things like auto-vendor-prefixing, nesting, etc.

    And, ignore all the “this is stupid” remarks of all those novice developers! A good developer doesn’t use such a demeaning language in the first place, but rather encourages positive discussion on which directions are better to follow, and most importantly *why*.

    For me, JSS has the upper hand due to encapsulation of styling and exposing the conflict-free classes, while CSSX has the upper hand in vanilla-CSS-inside-JavaScript and live updating of a stylesheet. Now it’d be great to have all of those features together! :}

    • 78

      Oh, I forgot to link to an example of component encapsulation of CSS in practice:

      You’ll notice in those examples that the conflict-free class names are applied to the elements from the component stylesheet’s `classes` property. Pretty neat huh!?

      In my previous comment I mentioned they’re randomly generated, but I meant to say just conflict-free. JSS just increments a counter so that classes are always unique. Inspect element to see…

    • 79

      Instead of fallaciously dismissing others’ opinions/questions, why don’t you answer some of the questions being asked by the “novice” developers to show us how smart you are? What problem does this solve? Why is this better? “Pretty Neat” is insufficient.

    • 80

      I’ve read alot of very decent motivations why this cssx is not-recommended.
      Maybe you should read them too and give a substantively respond.

      The opinions are about important things like: formality, portability, maintainability.

      And claiming that we all are “novice developers” means you’ve a poor way of thinking and setting yourself as a fool against the rest.
      In fact, to debunk, some fantastic enterprise developers have replied here who you calling novice.

      People like you disturbs the developers community.

  40. 81

    “You wouldn’t have to define new CSS classes because you would generate the CSS rules on the fly at runtime.”

    That’s enough for me to dismiss it. What about reusability, extensibility, performance, and maintenance? I really am having a hard time identifying the worth. You’re still using HTML and CSS, so why not use them in a way that is clear to the next dev to pick up your mess?

    • 82

      Krasimir Tsonev

      April 22, 2016 4:36 am

      CSS in JavaScript has its own use cases and I mentioned them several times in here. I’ll address reusability, extensibility, performance, and maintenance.

      reusability – just because the styles are in JavaScript this doesn’t mean that they can not be reused. In fact is exactly opposite. Writing them in JavaScript means that you have all the feature of the language to compose your styles. At the end is just constructing an object literal.

      extensibility – same as a above. JavaScript offers lots of ways for achieving extensibility. It’s like having a JavaScript object with its prototype and saying that it’s not extendable.

      performance – CSSX (and most of the css-in-javascript solutions) are not meant to be used for the basic styles. It’s about styles related to state. They apply when an action occur. Indeed some of the inline solution touch the DOM but that’s not the case with CSSX. It’s updating the content of a tag. And right now I’m thinking using CSSOM which is modifying a stylesheet with browser’s API without change the DOM at all.

      maintenance – sorry but I don’t see why you can’t maintain css-in-javascript solutions. It’s just JavaScript literals. So if that’s difficult for managing the problem is not in CSSX, it’s in how the developer approaches JavaScript architecting.

      • 83

        This just shows how much of a cancer JS has become to the web :)

  41. 84

    ITCSS is the real solution that is modular and scalable, Kickstarter are still using.

  42. 85

    ITCSS is based on rules that separated layers clearly. I won’t get lost into hundreds of classes. CSSX definitely not the solution if there are errors in JS.

  43. 86

    Richard Meijer

    April 20, 2016 9:12 am

    Wow, so much overreaction.

    There is a time and a place for everything. I think your alternative for JSS and CSSModules is a very cool idea and it looks nicely in line with what JSX does.

    I think much of the negativity here comes from not properly understanding the use-cases and/or the history of this particular style of creating components.

    Certainly, seperation of concerns is good approach. But I dont think CSSX is meant as a replacement for that. To me, this is a tool which helps you in developing components which can be used in either your own project or other projects. It is a means of bundeling all logic, markup and styling specific to the component so the consumer of the component does not need to include any dependencies. It also keeps your own project global markup and styling clear of component implementation specifics.

    Don’t let the negative comments get you down and please continue your work on CSSX.

  44. 87

    Radoslav Sharapanov

    April 20, 2016 10:00 am


  45. 88

    And why not just add the stylesheet dynamically in the header when necessary ?

  46. 89

    Shane Keulen

    April 20, 2016 6:51 pm

    We’ve been experimenting with this kind of thing for a bit. We’re using css-modules(with extract-text) to put anything static into our page. But we’re also using JSS to handle the dynamic portion of it. We’re using javascript objects but we could be using tagged template literals to get real css syntax.

    I think however that the ideal would be a new webpack loader.
    It should analyze your css and split out the static and dynamic code into two pipelines, static would be included with one loader (style-loader or extract-text) but the dynamic styles would be converted into a javascript object, and passed to jss and then attached to a react component (react-jss).

    This way we are able to write all for a component in the same file, use the same postcss pipeline on it, and we get dynamic css for free. I think this is actually doable, just need to find some time for it.

  47. 90

    James Chatterton

    April 20, 2016 7:18 pm

    Thank you for that. It’s a nice experiment. I like experiments and it’s an interesting one. Hope all the negative comments don’t stop you having fun with JavaScript.

  48. 91

    It’s really terrible how disrespectful many of the “developers” have been in the comments section here. I for one applaud you. This is an interesting idea, and whether it shakes out as feasible later is secondary in my opinion. It’s important for us to continue to keep an open mind so that the web can evolve. Sure, mistakes will be made, but that’s to be expected. This doesn’t mean we stop innovating or even imagining. Many of the particularly rude naysayers are more scared than anything else. Scared that they are no longer able to adapt to change (a crucial part of life as a developer) and think outside of their own comfort zone and accepted norms.

    Related – I think perhaps instead of adding style elements to the document, it would be better for CSS files to be generated and referenced via link tags. This will improve caching, since the CSS bits will not be re-fetched if only the JS or HTML changes. But this is something perhaps a bundler can handle with a CSSX loader.

  49. 92

    Nikhil Krishnan

    April 21, 2016 5:30 am

    This is make terrible, getting mess… Hoofs css is the simplest way to style the webpage. And need more advanced code use sass or less..

  50. 93

    Victor Longon

    April 21, 2016 7:58 am

    If they idea is to modularize and work in silos, I think the best why to do that is to have the “base styles” separated loading first for the whole app/page and then use css modules with webpack to load component specific styles. I even use Sass combined with css modules on my work flow and it works great.

    Having CSS declarations inside a component code is too much bloat, IMHO.

    But thanks for sharing your thoughts and your work!

  51. 94

    Web developers never-ending quest to overcomplicate the simple continues.

  52. 96

    Daniel Dafoe

    April 21, 2016 3:39 pm

    No thank you.

    If this actually took off (and I sincerely hope it does not), not only will someone come down the line with “Behold! CSS separate from JavaScript!”, but this is an absolute horror for code maintainability and reuse.

  53. 97

    Dane Simonsen

    April 21, 2016 4:18 pm

    Well, it looks like most of the people commenting on your article hate the concept, but it also appears most of those people are just regurgitating the same ol’ spiel that they heard from someone else about separation of concerns without really thinking about the usability of the library itself.

    If people want to continue keeping a closed mind about how development works without ever trrying to change the way its been done for the last decade, then it’s not really development so much as copying the last guy’s work.

    I have a project I am working now that is using XML files from multiple developers. All the elements have a multitude of dynamic and customized attributes that will either require a CSS sheet 20mb+ to handle all the possible cases, or a dynamic CSS system that can build it based upon parsing the elements. I believe this is where CSSX will shine. Why would I want to write styles for 10,000 possible elements that may not even get used 90% of the time, when I could just parse the elements at run-time and style as necessary.

    The fact that I can pack CSS, JS, HTML, and Images all into one file means that I only have a single resource to transfer for my entire application to work with whatever is thrown at it. This will simplify development time by months, remove the overhead of multiple transport requests, and provide a method to dynamically handle any possibilities that may arise in my particular case.

    Of course, I’m also not rebuilding a wordpress blog like the rest of these commenters, so maybe I should rethink how real world applications are actually made and used, and instead just complain about how someone created something new and useful and I just can’t figure out how it can be used.

    Thanks for your hard work, I’ll certainly be putting it to good use!

    (P.S. What about licensing? That’s far more important for a library to get used than worrying about all these idiots crying for split components without cause)

  54. 98

    Wow, yet another pointless library. Why would anyone want to use this? Seems like a total waste of a developers time. This does not fix any specific problem that I can see. People really need to stop fiddling and just get to work, build something useful. Use Sass, don’t use this garbage.

  55. 99

    I think this has huge potential but does need refining. This could be use a a font-size SASS which has enormous advantages such as removing the need for lots of @media (use the var w = $( window ).width(); ) in CSS but it may also be laggy in real world apps, one suggestion that could be use but not all the time is for both front and server side is for the CSSX to generate a static .css file on change saving CPU.

    Well done for pushing boundries

  56. 100

    now you may wonder why smashing publishes articles like this, really.

  57. 101

    Dimitar Christoff

    April 21, 2016 5:35 pm

    what about `componentWillUnmount(){}` in the example to show how it can remove redundant exported styles.

    It’s pretty cool that you can do this but not sure if you should. I think that this will / can be abused as creating and updating CSS rules for effects on the fly that pipelines via a reflow/repaint of the whole page is hardly ideal.

    imagine a resizable component that gets width as props:

    const {width} = this.props;

    .foo { width: `${width}px;` }

    return ;

    as you resize it for each even loop that fires, this will be updating stylesheets and rules and slowing it all down.

  58. 102

    CSJS attempts to do something like this without transpilation.

    I think the concept of transpilation, though it may come from a desire to improve the developer experience, is a mistake. I applaud your efforts to take this thought experiment into practice, but would advise you to consider creating modules that work without the need for additional dependencies and build tools.

  59. 103

    I have to say i’m a little disappointed to read some of the comments on here.

    Although I have to agree that the current state of Front-end development seems to be taking a wrong turn due to the myriad of new tools/frameworks/libraries popping up on an almost daily basis that we seem to have lost our way and trying to solve problems that don’t exist.

    I believe in keeping things simple as development can be hard enough as it is, these new tools are just over complicating the process making it hard to reason about solving an actual problem. I don’t see the major issue with just html/css/js as they are more than adequate and are continually evolving.

    i’m sure as the developer of cssx has learned a ton of new things but I wish these kind of things were kept to themselves as someone will think this is a great idea and begin using in production and the next thing we know is we have another Angular on our hands.

    Lets all take a deep breath and remember what we have in front of us.

  60. 104

    Thanks for the article. This is a really interesting experiment. I think a lot of the commenters are overreacting, although I agree with the basic idea that CSS and JS should stay in different files.

    That said, I can think of use cases where something like this could be useful. Imagine you’re building a web app for visualizing data (e.g., featuring a heatmap). In this interface, stylistic elements (e.g., colors and opacities on a heatmap) are used to represent numeric data associated with different elements. You cannot use CSS or a preprocessor to generate a finite list of classes for different states of these elements because the number of possible states is infinite (e.g., there is a theoretically infinite number of shades of colors or opacities that could be represented on the heatmap).

    You could use traditional JavaScript to apply inline styles, but say you have other associated elements on other parts of the DOM to which you want to apply the same styles (e.g., there is also a histogram on the page and each bar in the histogram is the same color as the associated region on the heatmap). And the numeric data for all elements of the interface could change based on user input or updates from the server. In this situation, it would be nice to handle style through dynamically rendered stylesheets, where related elements can be styled simultaneously, rather than through inline styles.

    In this situation, dynamic style properties used in data visualizations, are not elements of presentation in the same way that fonts and layout are. They are functions of data and algorithms used to process that data.

    Perhaps this is not a typical use case, but I work on things like this frequently in my current role, and I’ve never felt comfortable handling things like this in either CSS or JS. I think CSSX is the sort of thing that might be able to deal with this gracefully.

  61. 105

    Jose Antonio Blanco

    April 21, 2016 11:57 pm

    Great article! I may or may not agree with the approach, or with React, or with separation of concerns, but I find the topic and the detailed exposition of how you made it work with Babel extremely interesting.

    Honestly, I don’t understand all the backslash in the comments. We all should be exploring and pushing the boundaries of the web, and good ideas will win by meritocracy, as they always do.

  62. 106

    Kevin Lozandier

    April 22, 2016 12:05 am

    To buy into more into modern CSS APIs catering to modern APIs such as Web Component specs, how will you accommodate making things be better dynamic by native CSS custom properties, mixins (via @apply)?

    For example it seems ideal if you wer enabling the following in some way sensible to your current work:

    It’ll be interesting if he was proposing
    var size = 20

    To be transpiled to
    :root {
    –size: 20 // If globally defined, this would go inside :root

    const region {
    fontSize: “12px”


    To be
    –region: {
    font-size: 12px;

    So it can then be mixed in with `@apply`
    my-component {
    color: tomato;

    • 107

      Kevin Lozandier

      April 22, 2016 12:07 am

      I totally became lost trying to type all that on mobile; hope it somewhat makes sense, Tsonev!

  63. 108

    I understand why people are hating. I’ve only used JSX a little bit but I definitely see the value of coupling components with small pieces of html to the JavaScript that controls them. However, my take is that there is interesting potential with CSSX.

    One thing that could make CSSX more compelling is updating it to automagically limit the styles to the component. Angular 2 does this.

    When you include CSS inside an Angular 2 component, Angular automatically limits the scope of the CSS to the component by using attributes and attribute selectors. It is in effect a scoped stylesheet.

    For example, if the component includes the following rule:
    .sortable { color: blue; }
    gets converted and injected into a stylesheet like this:
    .sortable[_unique_id] { color: blue; }
    and every DOM element in the component has a `_unique_id` attribute added to it. See a screenshot here:

    That method of scoping is even more valuable than potential browser support for scoped stylesheets because child components have a different unique id and are not affected. It also allows components to have terse class names without fear of collision.

    I’m guessing that implementing that scheme into CSSX and React might not be too hard since React generates all the DOM itself.

    Also, on the point of clearing stylesheets, what about adding an `id` attribute to the style open tag to signify that the stylesheet should automatically clear any time a value changes? That would definitely simplify.

  64. 110

    Lewis Barclay

    April 22, 2016 8:32 am

    Krasimir, thanks for sharing.
    I especially like how you’ve detailed your experiences with AST and Babel.
    JSX + CSSX + JavaScript – seems to offer a subset of what Web components start with!

    I’m not convinced that anyone who aggressively disputes mixing markup / styling and a programming language has “given it 5 minutes”! Almost all SPA libraries and frameworks use some form of templating that is controlled by JavaScript – as soon as you create anything that allows you to do some kind of interpolation, you’re “mixing it all up”.
    Keep up the good work, I’m interested to see how this evolves.

  65. 111

    Jānis Kociņš

    April 22, 2016 9:00 am

    :set sarcasm on
    There is only one way to separate concerns – by file extension, anything else is wrong by default!

  66. 112

    Finally?!…This is something that never needed to happen. Keep them separate, very separate. Not with this at all.

  67. 113

    There seem to be a broad misunderstanding that “separation of concerns” somehow must imply styles and logic in different files. Another take on “separation of concerns” that make your code easy to understand, maintainable and reusable is by using isolated, testable components. This is the only meaningful context in which you can reason about the CSSX approach to dynamic styles in components.

    So I just want to thank the author for not only exploring the concept, but also for taking the time to explain the journey he took!

  68. 114

    Early in your article you wrote “Imagine a web component distributed as a single .js file and containing everything — markup, logic and styles.”

    That’s web components. Just use them instead. This is an abomination.

  69. 115

    Nikolay Talanov

    April 28, 2016 7:38 am

    I was scrolling/reading this article with thought that it’s some late 1st april joke…
    Especially syntax part. There is a lot of libs which allows you to emulate scoped css without messing up with default css syntax.
    And I’m not even talking about how terrible is “css in js” concept.

    Hope you didn’t wasted a lot of time on this abomination.

  70. 116


    May 2, 2016 9:28 pm

    Trying to keep an open mind and forget everything about web development, this looks definitely interesting. It’s nice the idea you load just unitial styles as normal CSS, when JS is loaded, start using CSSX.

    This provides an interesting contrast to conventional approaches where CSS is kept separate. CSS Modules strike a balance between a conventional approach and CSSX specific approach.

    f.i. Let’s suppose a framework that makes use of the new CSSX design paradigm, and explore material design themed components
    to create new components using css in JS.

    Wondering if there is performant issue using CSSX in a project, that have many components,
    to render js styles, browser needs to download the rendering lib first and most likely the entire js application.

    Another thing is I’ve thinking about if CSSX selectors across components could conflict.

  71. 117

    I appreciate your effort but I wonder how this is different from including a sass component file with the js? Then relying on sass for the dynamic parts. That feels like a simpler way to achieve the same thing?

  72. 118

    I like the babel plugin. That’s an idea worth developing. With some additions it could be a great preprocessor.

  73. 119

    Jitendra Vyas

    May 27, 2016 9:49 am

    Ok what is the main benefit of using CSSx for Server side rendered website (server-rendered css) over CSS in CSS?

  74. 120

    Ruben Lapolla

    June 2, 2016 9:55 pm

    Entiendo que seas un entusiasta apasionado del desarrollo web y enfoques tu desarrollo en CSSX “para tu caso particular”, según respondiste a un comentario anterior. Pero sugerir el concepto de “mezcla” entre CSS y JS como algo recomendable o una nueva tendencia próxima a desembarcar; es realmente pretensioso y resulta una muy mala práctica. Te sugiero que tomes un curso al respecto: TUDAI, cátedras Web 1 y Web2 en UNICEN: Exactas Tandil. Chau pibe!

  75. 123

    Leonardo Manrique

    June 12, 2016 11:13 pm

    The world is often unkind to new talent, new creations. The new needs friends.
    Thanks for an excellent tool.


↑ Back to top