CSS to JS dynamic insertion
Turn CSS rules into executable JS: a document.createElement("style") plus CSSStyleSheet.insertRule() call sequence, a per-declaration sheet.setProperty() version, or a styled-components template. Selectors, properties, @media / @supports conditions and @import are preserved (rules inside media queries are flattened into the same insertRule call). This is a decidable real transformation rather than dumping the source into a string; invalid CSS throws invalid-css.
Runs in your browserEvery computation happens in your browser — your data never leaves this device.
Result
The result can be copied directly.
Paste CSS to generate the JS insertion code
Characters: 0 · Rules: 0 · Media queries: 0 · Declarations: 0
What this tool does
- Inject a stylesheet at runtime instead of bundling all CSS.
- Turn CSS snippets from a design into styled-components quickly.
- Demonstrate CSSOM insertRule usage for teaching.
Example
Input
body { color: red; margin: 0 }
.btn { padding: 4px }Output
const style = document.createElement('style');
const sheet = document.head.appendChild(style).sheet;
sheet.insertRule('body { color: red; margin: 0 }', sheet.cssRules.length);
sheet.insertRule('.btn { padding: 4px }', sheet.cssRules.length);The output is runnable browser code; insertRule rule text is rebuilt from selectors and declarations rather than being the raw CSS string.
Frequently asked questions
What is the difference between the insertRule and setProperty versions?
The insertRule version inserts whole rules (keeping selectors and @media conditions) using sheet.cssRules.length as the index; the setProperty version sets declarations one by one, which suits inline styles on a single element, so media queries are only shown as comments.
How are media queries handled?
In the insertRule style, rules inside @media are joined into one @media (…) { … } rule with the condition preserved; the styled-components style nests media query blocks.
Are comments preserved?
No. Block comments are removed before parsing since they do not affect styles, so the output only contains rules.
What happens with invalid CSS?
Declarations without a colon, empty property or value, and input without any rule all throw invalid-css and show an error in the UI instead of silently emitting broken code.
Keywords:css to jsinsertRulestyled-componentsCSSStyleSheet