Type-safe CSS builder for TypeScript. ts-css lets you define selectors, declarations, media queries, and CSS variables with a fluent API, then serialize to CSS (optionally via Prettier). It is designed for generating styles in build tools or server-side environments with no DOM dependency.
- Author CSS as TypeScript instead of strings.
- Use typed properties via
CSSPropsfor safer style authoring. - Compose selectors and media queries programmatically.
- Produce deterministic CSS output you can prettify.
npm install @purestack/ts-cssyarn add @purestack/ts-csspnpm add @purestack/ts-cssimport { s } from '@purestack/ts-css'
const style = s()
style.select('body').css({
margin: '0',
fontFamily: "system-ui, -apple-system, 'Segoe UI', sans-serif",
})
style.select('.button').css({
background: '#1e90ff',
color: '#fff',
padding: '0.5rem 1rem',
borderRadius: '0.5rem',
})
const css = style.toPrettyCSS()
console.log(await css)Creates a root Style instance. If you pass a selector, it becomes the root selector; otherwise it starts empty.
const root = s()
const button = root.select('.button')Rules are created via .select() and values are set by .css() or .set().
const style = s()
style.select('.card').css({
padding: '1rem',
border: '1px solid #ddd',
}).select() automatically inserts a space unless you use a combinator or a leading pseudo selector.
const root = s('.card')
root.select('> .title') // ".card > .title"
root.select(':hover') // ".card:hover"
root.select('.icon') // ".card .icon"Use .media() to scope rules under @media.
const style = s('.layout')
style.css({ display: 'grid', gap: '1rem' })
style.media('max-width: 720px').css({ display: 'block' })Use .keyframes(name) to create an animation definition and .select() to
define its frames. Frame selectors are emitted without the parent selector.
const style = s()
const frames = style.keyframes('zt-memory-cycle')
frames.select('0%, 4%, 40%, 100%').transform('translateY(0)')
frames.select('12%, 28%').transform('translateY(-8px)')
style
.select('.zt-slab-memory')
.animation('zt-memory-cycle 8s ease-in-out infinite')
style
.select('.zt-slab-memory')
.media('prefers-reduced-motion: reduce')
.animation('none !important')Frames support from, to, percentages, and comma-separated percentage lists.
Use existing property methods, .css(), or .set() for declarations, including
motion-path properties such as .set('offset-distance', '100%').
Repeated names in the same container reuse their block; repeated frame selectors
merge declarations using the normal style builder behavior. Definitions stay
inside their containing media or scope block and participate in revision tracking.
Names are trimmed and must be non-empty; supply a valid CSS animation name and
valid frame selectors. Names are emitted without rewriting and remain global
inside @scope. Use distinct names for animations with different definitions.
Values beginning with $name or --name are automatically converted to var(...).
const style = s('.btn').css({
color: '$text',
background: '--brand, #ff44aa',
})
// => color: var(--text); background: var(--brand, #ff44aa);Use .use() to merge declarations from another style into the current one.
const base = s().css({ fontSize: '14px', lineHeight: '1.4' })
const item = s('.item').use(base).css({ color: '#333' })import { s } from '@purestack/ts-css'
const style = s('.card')
style.css({
borderRadius: '12px',
border: '1px solid #e5e7eb',
padding: '1rem',
})
style.select('> .title').css({
fontWeight: '600',
marginBottom: '0.5rem',
})
style.select('.actions').css({
display: 'flex',
gap: '0.5rem',
})
style.select('.actions > .btn').css({
borderRadius: '999px',
padding: '0.4rem 0.9rem',
})import { s } from '@purestack/ts-css'
const baseText = s().css({
fontSize: '16px',
lineHeight: '1.5',
})
const layout = s('.layout').use(baseText).css({
display: 'grid',
gridTemplateColumns: '1fr 1fr',
gap: '1rem',
})
layout.media('max-width: 800px').css({
gridTemplateColumns: '1fr',
})import { s } from '@purestack/ts-css'
const theme = s(':root').css({
'--brand': '#ff44aa',
'--bg': '#111827',
'--fg': '#f9fafb',
})
const button = s('.button').css({
background: '$brand',
color: '$fg',
border: '1px solid --brand, #ff44aa',
})StyleextendsBaseStyleand stores declarations in a map and nested selectors as children..select()creates a child style using the parent selector + the new selector (with automatic spacing unless a combinator or:is used)..media()creates a sibling style under@media(...)and targets the current selector inside that media block..keyframes()creates a named animation block whose children are unprefixed frame selectors..toCSS()serializes each container in a deterministic order: normal selectors first, then@media,@scope, and@keyframesblocks, preserving creation order within each group via internal IDs..toPrettyCSS()runs the output through Prettier (parser: css) with default formatting options.
Creates a Style instance. If a selector is provided, it becomes the root selector.
set(name, value)- set a single property (camelCase or kebab-case).css(object)- set many properties at once usingCSSProps.select(selector)- create or access a nested selector.media(query)- create or access a@media(...)block scoped to this selector.keyframes(name)- create or access a named animation; select its frames withselect().use(style)- shallow-merge declarations from another style into this one.toCSS()- serialize to CSS string.toPrettyCSS(options?)- serialize and format using Prettier.
use()merges only property declarations, not child selectors.select()preserves insertion order; repeated calls to the same selector return the same node.media()uses@media(${query})if you pass a bare query (without@media).autoVar()converts$nameand--namevalues tovar(...); other values are untouched.- Output uses Windows-style CRLF in some internal joins;
toPrettyCSS()normalizes tolf.
ts-css is designed to pair with ts-html and ts-ssg:
import { s } from '@purestack/ts-css'
import { h } from '@purestack/ts-html'
const style = s()
style.select('.hero').css({
fontSize: '32px',
fontWeight: '700',
})
const page = h('html').push(
h('head').push(h('style').raw(style.toCSS())),
h('body').push(h('div').class('hero').text('Hello')),
)
console.log(page.toHtml())Returns raw CSS as a string.
Formats output using Prettier (parser: css) with defaults:
tabWidth: 2endOfLine: 'lf'
Exports:
s(selector?)->StyleStyle(extendsBaseStyle)getColors,getGradient(color utilities)
Key BaseStyle methods:
set(name, value)css({...})select(selector)media(query)keyframes(name)use(style)toCSS()toPrettyCSS(options?)
ts-css provides helpers for color conversions and gradients:
import { getColors, getGradient } from '@purestack/ts-css'
const shades = getColors('#1e90ff', 30, 20, 5)
const stops = getGradient('#21a8c3', '#a50d60', 6, 'hsl')CSSProps is a large type union of CSS properties used by .css() and property-specific methods on Style. It provides autocomplete and helps catch invalid property names or values.
The generator combines the original src/meta/cssProps.ts with the handwritten
additions in src/meta/cssProps2.ts. Maintain new properties in cssProps2.ts
using the same $, desc, and optional values.value structure. Existing
properties, including vendor-prefixed and older names, remain available.
Regenerate the fluent methods and explicit property types from the repository root:
yarn tsx packages/ts-css/src/meta/generateStyle.tsThis updates src/style.ts and src/cssProps.ts. Keep property additions in the
metadata so they survive subsequent generator runs.
yarn workspace @purestack/ts-css test@purestack/ts-htmlfor type-safe HTML generation@purestack/ts-ssgfor a minimal static-site composition layer
MIT