- Notifications
You must be signed in to change notification settings - Fork9
💈 CSS-in-JS 101: All you need to know
License
stereobooster/css-in-js-101
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
- What is CSS-in-JS?
- Inline styles
- Style tag
- CSS Modules
- Global Name Space, Globally Unique Identifier
- Dependencies
- Minification
- Sharing Constants, variables in CSS
- Non-deterministic Resolution
- Isolation
- Theming
- SSR, Server-Side Rendering
- Zero runtime dependency
- CSS-in-JS implementation specific features
- Progressive enhancement, graceful degradation
- Uncovered subjects
CSS-in-JS is an umbrella term for technologies which help you define styles in JS in more component-approach-way. The idea was introduced by@vjeux in 2014. Initially, it was described as inline styles, but since then battlefield changed a lot. There are about 50 different solutions in this area.
- @vjeux, 2014
- Big list of CSS-in-JS solutions
- Comparison of CSS-in-JS by styled-components
- Yet another comparison
This is built in feature of React. You can pass styles as an object to the component and it will be converted to the string and attached as style attribute to the element.
- No
global namespace Full isolation- No
non-deterministic resolution - Clear
dependencies Dead code eliminationVariables, Passing variable from JS to CSS
- Code duplication in case of SSR.
- Additional costs in JS payload. Remember that styles which are embedded in JS are not for free. It is not only about download time, it is also about parsing and compiling. Seethis detailed explanation by Addy Osmani, why JS is expensive
- No media queries (
@media) - No CSS animations (
@keyframes) - No pseudo classes (
:hover) - No web fonts (
@font) - No autoprefixer (well there isinline-style-prefixer)
TODO: verify
JSX:
hundred_length_array.map(x=><divkey={x}style={{color:"#000"}}></div>)
Generated HTML:
<divstyle="color:#000"></div>...(98 times)<divstyle="color:#000"></div>
@mxstbr differentiateInline styles andCSS-in-JS. ByInline styles he means React built-in support for style attribute and byCSS-in-JS he means a solution which generates CSS and injects it via style tag.
On the other hand,CSS-in-JS is the term coined by@vjeux in 2014 and he meantInline styles.Inline styles is not React-only feature. There is, for example, Radium which also usesinline styles.
So I would suggest to useCSS-in-JS as an umbrella term and specify implementation:
- inline styles
- style tag. Also can be referred as "style element" or "real CSS"
- mixed (like Radium)
This approach is alternative toInline styles. Instead of attaching styles as property to the element you are inserting real CSS in style tag and append style tag to the document.
Pros and cons can vary from implementation to implementation. But basically, it looks like this:
- (Almost) No
global namespace - (Almost)
Full isolation - (Almost) No
non-deterministic resolution - Clear
dependencies Dead code eliminationVariables(depends on implementation)- No code duplication in case of SSR
- Additional costs in JS payload (depends on implementation)
- Media queries (
@media) - CSS animations (
@keyframes) - Pseudo-classes (
:hover) - Web fonts (
@font)
Cons depend on implementation.
constMyStyledComponent=props=><divclassName="styled"> Hover for red<styledangerouslySetInnerHTML={{__html:` .styled { color: blue } `}}/></div>
Generated HTML:
<divclass="styled"> Hover for red<style> .styled {color: blue }</style></div>
A CSS Module is a CSS file in which all class names and animation names are scoped locally by default. All URLs (url(...)) and @imports are in module request format (./xxx and ../xxx means relative, xxx and xxx/yyy means in modules folder, i. e. in node_modules).
- (Almost) No
global namespace - (Almost)
Full isolation - (Almost) No
non-deterministic resolution - Clear
dependencies - (Almost)
Dead code elimination Variables, Sharing variables in CSS and exposing it to JS- No Code duplication in case of SSR
- No Additional costs in JS payload.
- Media queries (
@media) - CSS animations (
@keyframes) - Pseudo-classes (
:hover) - Web fonts (
@font) - Autoprefixer
See all points with "(Almost)"
Strictly speaking, there are no official solutions to those problems inCSS Modules, but there is some work in this direction. Correct me if I'm wrong if there is one, why isn't it promoted?
- Comment by @sokra on critical CSS
- isomorphic-style-loader
- Support Tree shaking of CSS
- Atomic CSS a la styletron
- CSSO scopes
All declarations in CSS are global, which is bad because you never know what part of application change in global scope will affect.
- Attach styles to each element (
Inline styles) - Use Globally Unique Identifiers for classes (
CSS modules) - Use naming conventions (BEM and others)
Ability to programmatically resolve dependency between component (JS and HTML) and styles, to decrease error of forgetting to provide appropriate styles, to decrease fear of renaming CSS classes or moving them between files.
- bundle styles with-in component (CSS-in-JS)
import styles from "styles.css"(CSS modules)
Dead Code Elimination
There is more than one aspect of minification. Let's explore:
This is the simplest approach - remove whitespace, minify color name, remove unnecessary quotes, collapse CSS rules etc. See big list of minifiershere
In CSS modules and CSS-in-JS you do not use class names directly, instead, you use JS variables, so class names can be easily mangled.
Note: This type of minification is not possible for traditional CSS.
importstylesfrom"styles.css";<divclassName={styles.example}/>
styles compiles to{ example: "hASh"}
Because there is no connection between JS/HTML and CSS, you cannot be sure if it is safe to remove some parts of CSS or not. If it is stale or not? If it is used somewhere or not?
CSS-in-JS solves this problem because of a link between JS/HTML and CSS is known, so it is easy to track if this CSS rule required or not.
DependenciesCritical CSS
The ability of a system to extract and inline styles in head required for current page viewed by the user not more nor less.
Note: this is slightly different from the definition by@addyosmani,which defines critical as above-the-fold.
import{StyleSheet,css}from'aphrodite'conststyles=StyleSheet.create({heading:{color:'blue'}})constHeading=({ children})=>(<h1className={css(styles.heading)}>{children}</h1>)
import{StyleSheetServer}from'aphrodite'const{ html, css}=StyleSheetServer.renderStatic(()=>ReactDOMServer.renderToString(<App/>))
DependenciesDead Code EliminationSSR
In CSS modules and CSS-in-JS you do not use class names directly, instead, you use JS variables, so class names can be easily mangled. The same as in "Minification of class name". But we can go further - generate smaller classes and reuse them to achieve smaller CSS
Note: This type of minification is not possible for traditional CSS.
import{injectStyle}from'styletron-utils';injectStyle(styletron,{color:'red',display:'inline-block'});// → 'a d'injectStyle(styletron,{color:'red',fontSize:'1.6em'});// → 'a e'
There are different approaches.
- CSS variables
- Can I use css variables
- CSS variables in preprocessors, like PostCSS, SASS etc.
This is mainly a feature ofCSS modules with variables.
/* colors.css */@value primary:#BF4040;
Sharing variables in CSS:
@value primaryfrom'./colors.css';.panel {background: primary;}
Exposing it to JS:
import{primary}from'./colors.css';// will have similar effectconsole.log(primary);// -> #BF4040
This is only possible withCSS-in-JS. This approach gives maximum flexibility and dynamics.
importstylingfrom'styling'import{baseColor}from'./theme'exportletbutton=styling({backgroundColor:baseColor})
Overriding theme variables
Resolution depends on the order of declarations in stylesheets (if declarations have the same specificity).
Because of CSS cascading nature and Global Name Space, there is no way to isolate things. Any other part code can use more specificity or use!important to override your "local" styles and it is hard to prevent this situation
Strictly speaking, only inline styles gives full isolation. Every other solution gives just a bit more isolation over pure CSS, because of solving Global Name Space problem.
Two CSS properties walk into a bar.
— Thomas "Kick Nazis out, @jack" Fuchs (@thomasfuchs)July 28, 2014
A barstool in a completely different bar falls over.
The idea is to be able to change the look of existing components without the need to change actual code.
This way you can override styles based on "class names" (keys of objects in case of inline styles).
WithCSS modules:
importthemefrom'./MyComponentTheme.css';<MyComponenttheme={theme}/>
Same with inline styles:
consttheme={foo:{'color':'red'},bar:{'color':'blue'}};<MyComponenttheme={theme}/>
This way you can override styles based on variables passed to the theme. The theme basically works like a function - accepts variables as input and produce styles as a result.
Variables, Passing variable from JS to CSS
Make sure thatCSS-in-JS solution doesn't brake default React isomorphism e.g. you are able to generate HTML on the server, but not necessary CSS.
Be able to prerender CSS on the server the same way as HTML can be prerendered for React.
import{StyleSheet,css}from'aphrodite'conststyles=StyleSheet.create({heading:{color:'blue'}})constHeading=({ children})=>(<h1className={css(styles.heading)}>{children}</h1>)
import{StyleSheetServer}from'aphrodite'const{ html, css}=StyleSheetServer.renderStatic(()=>ReactDOMServer.renderToString(<App/>))
TODO: add example withInline Styles
Critical CSS
Almost allCSS-in-JS solutions have runtime dependency e.g. library required to generate styles at runtime and CSS encoded as JS.
Some solutions do not have this issue, they basically vanished after build step. Examples:CSS modules, linaria.
importReactfrom'react';import{css,styles}from'linaria';consttitle=css`text-transform: uppercase;`;exportfunctionApp(){return<Header{...styles(title)}/>;}
Transpiled to:
.title__jt5ry4 {text-transform: uppercase;}
importReactfrom'react';import{styles}from'linaria/build/index.runtime';consttitle='title__jt5ry4';exportfunctionApp(){return<Header{...styles(title)}/>;}
React can target different platforms, not just DOM. It would be nice to haveCSS-in-JS solution which supports different platforms too. For example:React Native,Sketch.
constcolor="red"conststyle={color:'red',}
constcolor="red"conststyle=` color:${color};`
Does it depend on React or not?
If build step required or not?
SSRProgressive enhancementDynamic
If you can pass values to CSS at runtime.
Note: it is not the same asVariables, Passing variable from JS to CSS, for example inlinaria you can pass variables from JS to CSS, but only at build time.
Note 2: cannot stop myself from drawing analogy between static and dynamic type systems.
Build stepVariables, Passing variable from JS to CSS
If your component has pretty simple structure and you care more about how it looks instead of markup (which most likely will bediv anyway). You can go straight to write CSS and library will generate components for you.
importReactfrom'react'import{Button}from'./style.css'<Button> Panic</Button>
importReactfrom'react'importstyledfrom'styled'constButton=styled.button` background-color: red;`;<Button> Panic</Button>
If there are special perks for developer tools?
emotion supports source maps for styles authored in javascript
If you do not know what is it read thisarticle.
In the context ofCSS-in-JS it boils down to one question - will your website be styled with disabled JS.
The first requirement would be to have some HTML rendered on the server (SSR orsnapshoting). After this you have two options:
- prebuild CSS e.g.
Build steprequired - rendered CSS e.g.
CSS SSRrequired
SSRBuild step
Seethis post
Also known ascode splitting,dynamic import
Async component is a technique (typically implemented as a higher order component) for loading components withdynamic import. There are a lot of solutions in this field here are some examples:
- Dynamic import is the TC39 proposal.
Webpack has a feature to split your codebase into “chunks” which are loaded on demand. Some other bundlers call them “layers”, “rollups”, or “fragments”. This feature is called “code splitting”.
This works for mostCSS-in-JS solutions because CSS is bundled inside JS. This is a more complicated task for CSS modules. See:Guide To JavaScript Async Components.
Also known asimmutable,functional,utility-class.
Idea boils down to use one property per class, so you create required look by composing more than one class. Because each class contains only one property, you do not override those properties and this can be interpreted as immutability.
Do not confuse withAtomic CSS framework.
Basically CSS3 animations. Pros: can be GPU accelerated.
Also known asinteractive.
Basically JS animations. Pros: can be interrupted.
About
💈 CSS-in-JS 101: All you need to know
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors2
Uh oh!
There was an error while loading.Please reload this page.
