class2css
v1.2.9
Published
**Class2css** is a utility that lets you write compact and semantic class strings in HTML, and it will automatically generate the corresponding CSS.
Readme
Class2css
Class2css is a utility that lets you write compact and semantic class strings in HTML, and it will automatically generate the corresponding CSS.
💡 What is Class2css?
Class2css parses specially structured class attributes into an AST (Abstract Syntax Tree) and generates actual CSS rules. It supports responsive design, advanced selectors, and dynamic declarations.
🔧 Installation
npm install class2css🧱 Class Syntax Structure
A class string may include:
Media Query(mq):>md,<lg,>768Selector(sel):>.child,>>.descendant,+p,~.sibling,:h,:fDeclaration(decl):c-red,fs-16,w-100,m-10-20
<div class=">md >>.title c-red fs-20 ^ fs-14">Hello</div>^resets the previous media queries and selectors.- Without a selector, the declaration applies to the current element.
📦 API
parseToAST(input: string, options?: { extraAttributes?: string[] }): ASTBlock[]
generateCSS(blocks: ASTBlock[], options?: { themePath?: string }): stringparseToAST: Convert class string to AST.generateCSS: Convert AST to CSS.themePath: Directory containingconfig.scssandstyles.json.
⚙️ Configuration Files
config.scss
Define variables and tokens:
$screens: (
sm: 480px,
md: 768px,
lg: 1024px
);
$colors: (
red: #ff0000,
green: #00aa00
);
$variables: (
border-size: 1px
);styles.json
Define static reusable class groups:
{
".btn": "bg-blue c-white fs-14 py-10 px-20",
".bar": ">md bg-green <md bg-red"
}🧩 Components of Class Syntax
📐 Media Queries (mq)
- Use
>md,<lg,>768,<1024etc. - Can combine multiple for complex responsive control.
🧭 Selectors (sel)
>div: direct child>>.title: any descendant+p: adjacent sibling~.box: general sibling:h,:f,:nth[2],:fc,:lc,:not(.active)
🎨 Declarations (decl)
Declaration format:
[name]-[value][-i]Examples:
c-red:color: redfs-20:font-size: 20pxw-100-min:50:width: 100px; min-width: 50pxp-10-20:padding: 10px 20pxgrid-auto/100-1fr: grid templateflex-rr-w: flex row-reverse with wraplh-1.6:line-height: 1.6bd-2-solid-red: shorthand border
Use -i to add !important.
🧠 AST Format
interface MediaQuery {
type: 'min' | 'max';
value: string;
}
interface Declaration {
type: string;
raw: string;
}
interface ASTBlock {
mediaQueries: MediaQuery[];
selectors: string[];
declarations: Declaration[];
attributes?: string[];
}📘 Example
<div class=">md >>.card c-red fs-18 ^ fs-14">Content</div>Generated CSS:
@media screen and (min-width: 768px) {
.\>md\>\>.card.c-red.fs-18 .card {
color: red;
font-size: 18px;
}
}
.fs-14 {
font-size: 14px;
}✨ Features
- ✅ Mobile-first responsive support
- ✅ Nested selectors
- ✅ Dynamic media queries
- ✅ Custom SCSS tokens
- ✅ Static class expansion via JSON
📄 License
MIT
🙌 Credits
Made with ❤️ by Le Cong Thanh.
