Skip to content

Instantly share code, notes, and snippets.

@streamich
Last active August 19, 2021 13:08
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save streamich/09d99716d05304fe8c4ff9cf20d3c7d7 to your computer and use it in GitHub Desktop.
Save streamich/09d99716d05304fe8c4ff9cf20d3c7d7 to your computer and use it in GitHub Desktop.

tweet-css

Smallest possible CSS-in-JS library.

  • Try demo
  • 178 bytes (minified and gzipped)
  • Source code fits in a tweet
  • Dynamic 4th generation styling
  • "jsxstyle" interface
  • Pure React — no side effects
  • Functional styles
  • Theming support
  • Universal rendering with no additional setup
  • Inspired by nano-style

Usage

import {createElement as h} from 'react';
import {css} from './lib';

const jsx = css(h);

const Button = jsx('button', (props) => `
  color: white;
  background: ${props.primary ? 'blue' : '#555'};
  padding: 16px;
`);

<Button>Cancel</Button>
<Button primary>Submit</Button>

Library

ES5 version:

var id = 0;

exports.css = function(h) {
  return function(tag, css) {
    return function(props) {
      var cn = "_" + id++;
      var newProps = Object.assign({ className: cn }, props);
      var rawCss = "." + cn + "{" + css(newProps) + "}";
      return [
        h("style", {
          dangerouslySetInnerHTML: { __html: rawCss }
        }),
        h(tag, newProps)
      ];
    };
  };
};

ES6 version:

let id = 0;

export const css = h => (tag, css) => props => {
  const className = "_" + id++;
  const newProps = { ...props, className };
  const rawCss = "." + className + "{" + css(newProps) + "}";
  return [
    h("style", {
      dangerouslySetInnerHTML: { __html: rawCss }
    }),
    h(tag, newProps)
  ];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment