DEV Community

Artur Czemiel
Artur Czemiel

Posted on

5 4

CSS in JS -> write your own engine

The why?!

Nowadays advanced frameworks like React, Vue, Angular, etc. are using CSS in JS syntax. You should write your own CSS in JS minimal engine to understand what's going on under the hood.

Javascript

function o2s(o, className) {
  var elm = new Option();
  Object.keys(o).forEach(function() {
    (elm.style)[a] = o[a];
  });
  return `.${className}{\n${elm.getAttribute("style")}\n}`;
}
/**
 * Class responsible for small css functionalities rendered in HTML like menu
 *
 * @export
 * @class CSSMiniEngine
 */
export class CSSMiniEngine {
  classes = [];
  /**
   * add css class with css params
   *
   * @memberof CSSMiniEngine
   * @param {Partial<CSSStyleDeclaration>} o
   * @param {string} className
   */
  addClass = (o, className) => {
    this.classes.push(o2s(o, className));
  };
  /**
   * compile to style tag in head
   *
   * @memberof CSSMiniEngine
   */
  compile = () => {
    const head = document.head || document.getElementsByTagName("head")[0];
    const style = document.createElement("style");
    head.appendChild(style);
    style.type = "text/css";
    style.appendChild(document.createTextNode(this.classes.join("\n")));
  };
}

Enter fullscreen mode Exit fullscreen mode

Typescript

function o2s(o: Partial<CSSStyleDeclaration>, className: string) {
  var elm = new Option();
  Object.keys(o).forEach(function(a: string) {
    (elm.style as any)[a as any] = o[a as any];
  });
  return `.${className}{\n${elm.getAttribute("style")}\n}`;
}
/**
 * Class responsible for small css functionalities rendered in HTML like menu
 *
 * @export
 * @class CSSMiniEngine
 */
export class CSSMiniEngine {
  classes: string[] = [];
  /**
   * add css class with css params
   *
   * @memberof CSSMiniEngine
   * @param {Partial<CSSStyleDeclaration>} o
   * @param {string} className
   */
  addClass = (o: Partial<CSSStyleDeclaration>, className: string) => {
    this.classes.push(o2s(o, className));
  };
  /**
   * compile to style tag in head
   *
   * @memberof CSSMiniEngine
   */
  compile = () => {
    const head = document.head || document.getElementsByTagName("head")[0];
    const style = document.createElement("style");
    head.appendChild(style);
    style.type = "text/css";
    style.appendChild(document.createTextNode(this.classes.join("\n")));
  };
}

Enter fullscreen mode Exit fullscreen mode

Usage example

Instantiate

const cssEngine = new CssMiniEngine()
Enter fullscreen mode Exit fullscreen mode

Create Class

const className = "MyClass"
cssMiniEngine.addClass(
      {
        visibility: "visible",
        position: "fixed",
        background: "transparent",
        border: "0",
        textAlign: "center",
      },
      className
);

Enter fullscreen mode Exit fullscreen mode

Use it

In pure js

const div = document.createElement("div")
div.classList.add(className)

Enter fullscreen mode Exit fullscreen mode

In React

export const MyDiv = () => (
  <div className={className}>Hello</div>
)
Enter fullscreen mode Exit fullscreen mode

In the end call

cssEngine.compile()

Enter fullscreen mode Exit fullscreen mode

So it will insert all your classes to DOM as a style tag
Thank you for reading!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay