#Styling
Style pages with CSS Modules, a Go-native Tailwind, and a built-in CSS pipeline.
Krate ships a CSS pipeline built into the compiler: CSS Modules, Go-native
Tailwind, duplicate-declaration folding, minification, and @import inlining. No
PostCSS or extra tooling is required.
#CSS Modules
Files named *.module.css are scoped automatically:
/* Card.module.css */
.card {
padding: 1rem;
border-radius: 8px;
}import styles from './Card.module.css';
export default function Card() {
return <div class={styles.card}>...</div>;
}- Class names are hashed:
className->className_<fnv32a_hash>. - The hash is FNV-32a of the absolute file path (6-char base36), so it's deterministic per file and stable across builds.
- Scoping is tokenizer-based: strings, comments,
url(...), attribute selectors, and:global(...)are handled correctly.:global(.x)stays unscoped (the wrapper is removed); a bare:globalor:localswitches the mode for the rest of the selector. @keyframesnames defined in a module are scoped, andanimation/animation-namereferences are rewritten; use@keyframes :global(name)to keep a name global.composes: other;,composes: a b;,composes: x from global;andcomposes: x from "./base.module.css";add the composed classes tostyles.<name>and are removed from the output CSS.- Dashed names have camelCase aliases:
styles["card-title"]andstyles.cardTitleare the same class.
#Tailwind CSS
Krate's Tailwind is Go-native - no PostCSS, no Node at build time - and follows the Tailwind v4 CSS-first model.
tailwind: {
enabled: true,
scanDirs: ["src"], // or: content: ["./src/**/*.{tsx,mdx}"]
preflight: true, // base reset (default; false to opt out)
strict: false, // warn on classes that produce no rule
darkMode: "media", // "media" | "class" | "selector"
}Tailwind is off until enabled: true is set. If a tailwind.config.{ts,js,mjs}
file exists, or your CSS uses @tailwind or @import "tailwindcss", while it
is off, the build warns once (KR7140) instead of
quietly shipping a nearly empty stylesheet.
#CSS-first directives
Krate reads the Tailwind v4 CSS-first directives from your stylesheets (files under the scan directories and the CSS your pages import), uses them to configure the generator, and removes them from the shipped CSS:
@import "tailwindcss" prefix(tw) important; /* modifiers: prefix(), important, source() */
@theme {
--color-brand-500: #ff4d4d;
--spacing: 0.3rem; /* base spacing unit */
--text-xl--line-height: 1.6;
--font-display: "Playfair Display", serif;
--animate-fadein: fadein 1s ease-out;
@keyframes fadein { from { opacity: 0 } to { opacity: 1 } }
}
@source "../shared-ui"; /* extra directory to scan */
@source not "../shared-ui/legacy"; /* excluded directory */
@source inline("underline p-{1,2}"); /* always generate these */
@utility tab-4 { tab-size: 4; } /* static custom utility, works with variants */
@utility pad-* { padding: --spacing(--value(integer)); } /* functional: pad-3 */
@custom-variant theme-mid (&:where([data-theme=mid] *));
@custom-variant dark (&:where(.dark, .dark *));-
@themeis parsed with real brace matching, so nested@keyframesand values containing}work. Supported namespaces:--color-*(incl.name-<shade>),--spacing,--spacing-*,--text-*(and--text-*--line-height),--font-*,--font-weight-*,--tracking-*,--leading-*,--radius-*,--shadow-*,--opacity-*,--breakpoint-*,--container-*,--animate-*.--color-*: initial(or any--ns-*: initial, or--*: initial) resets a namespace.@theme inline,staticanddefaultare accepted;@theme referencemakes variables usable by utilities without emitting them. Variables for namespaces Krate has no utilities for (--ease-*,--blur-*, ...) are still emitted and reported as a warning. -
Theme variables are emitted in
@layer theme { :root, :host { ... } }. Krate emits every user-defined@themevariable (v4 emits only the used ones unlessstatic) plus any built-in theme variable you reference asvar(--color-red-500),var(--spacing), etc. in your CSS or scanned files, including thebg-(--color-blue-500)class shorthand. -
@themevariables stay live, as in Tailwind v4. Utilities read them throughvar(), so overriding one re-themes every utility that uses it:@theme { --color-primary: #123456; } .dark { --color-primary: #fedcba; }@theme inlinecopies the value into the utility instead, so an override has no effect there.@theme referencevariables are inlined too. -
@utilityfollows Tailwind v4. A functional utility (name-*) takes its value from the rest of the class (name-VALUE) through--value()and its modifier (name-VALUE/MODIFIER) through--modifier();--spacing()wraps either. Both accept, tried in order:integer,number,percentage,ratio(value only),[type]for an arbitrary value of that type ([length],[color],[percentage],[number],[integer],[ratio],[url],[image],[position],[bg-size],[line-width],[family-name],[generic-name],[absolute-size],[relative-size],[angle],[vector], or[*]for any),"literal"keywords, theme namespaces such as--color-*or your own--tab-size-*, and--default(x)for a class with no value or modifier. A declaration whose call cannot resolve is dropped, and a class that resolves nothing generates nothing, sobg-red-500/50is not a match for a utility that has no--modifier().@theme { --tab-size-github: 8; } @utility tab-* { tab-size: --value(--tab-size-*, integer, [integer]); } @utility text-fit-* { font-size: --value(--text-*, [length]); line-height: --modifier(--leading-*, [length], [*]); /* text-fit-lg/tight */ &:hover { text-decoration: underline; } @media print { font-size: 12pt; } @variant dark { color: white; } }Nested rules (
&:hover,.parent &,& > *), at-rules (@media,@supports,@layer),@variant name { ... }and@applywork inside the body, in static and functional utilities alike; they are written as CSS nesting inside the class rule. Only@themevariables count for--value(--spacing-*)(Tailwind v3's numeric spacing scale is not a v4 theme variable). Output is checked against Tailwind v4 ininternal/css/testdata/tailwind_utility_golden.json.@custom-variantsupports the(selector)form,@media/@supports, and the singleselector { @slot; }block form. -
@configand@pluginare not supported: they are removed and reported as a warning (Krate readstailwind.config.{ts,js,mjs}from the project root itself; JS plugins are never executed).@variantinside rules is reported and left in place. -
Warnings are printed once per build.
#Layering
The generated stylesheet uses cascade layers like Tailwind v4:
@layer theme, base, components, utilities;
@layer theme { :root, :host { --color-brand-500: #ff4d4d } }
@layer base { /* preflight */ }
@layer utilities { /* .p-4, .hover\:bg-red-500, ... */ }
@keyframes ... /* used animations, outside the layers */The Tailwind sheet is linked before page CSS. Your unlayered CSS therefore
beats both preflight and utilities (same as v4), your own @layer base { ... }
rules come after preflight, and utilities beat preflight and any layered
base/components rules. To make a utility win over an unlayered component rule,
put that rule in @layer components.
Migrating a reset: a global reset such as *, *::before, *::after { margin: 0; padding: 0 } written as plain unlayered CSS now beats every utility (p-3,
mt-2 compute to 0). Unlayered CSS beats Tailwind utilities, so put resets in
@layer base { ... }.
#@apply
@apply is supported anywhere inside a rule body (.btn { @apply px-4 py-2; },
including on one line). Plain utilities are expanded in place in utility sort
order; animation utilities also emit their @keyframes. Variant utilities
(@apply hover:underline md:flex;) and descendant-selector ones (space-x-*)
become CSS nesting inside the rule (@media (hover: hover) { &:hover { ... } }),
after the rule's own declarations, so they need a browser with native CSS
nesting. Unknown utilities cannot be expressed and are reported as build
warnings. @tailwind directives are stripped, and @layer blocks are left as
authored.
- A candidate scanner extracts Tailwind tokens from the whole file, in the
spirit of Tailwind's own extractor: it does not depend on string tokenization,
so TSX, TS, MDX, Markdown and HTML (including prose with apostrophes, regex
literals and
${}template interpolations) all work, and arbitrary values and variants containing= ' " & > +(data-[state=open]:p-4,[&>svg]:size-4,has-[>img]:,nth-[2n+1]:,content-['x'],bg-[url('/a.png')],bg-(--brand)) are kept. As in Tailwind v4, plain words in scanned prose such ashidden,table,blockorbordercan generate the matching utility. Dynamic fragments likebg-${x}generate nothing. - With
tailwind.strict: true, candidates that look like utilities but matched no rule are printed as a build warning. - The CSS generator maps classes to rules from a built-in rule set. Output is deterministic - identical inputs always produce the same stylesheet.
- Theme configuration lives in
tailwind.config.ts. It is statically parsed by default (no Node required); settailwind.executeConfig: trueto evaluate it in-process instead.theme.extendmerges onto the defaults; top-levelthemekeys replace them. Supported keys includecolors,spacing,screens,fontFamily(strings or arrays),fontSize(including the[size, { lineHeight }]form),letterSpacing,animation,keyframes,borderRadius,boxShadow,darkMode('class','media',['selector', '.x'],['class', '[data-mode="dark"]']),prefixandimportant. Unsupported or statically unevaluable entries (plugins,presets,safelist,screenswith{ min, max }, computed values) are reported as build warnings, never ignored silently.
<div class="p-4 hover:bg-zinc-100 dark:bg-zinc-900 w-[100px] -mt-2 bg-blue-500/50">
Responsive, dark-mode aware, arbitrary values, negatives, color opacity.
</div>Supported features:
- Variants: state (
hover:,focus:,active:,disabled:, ...),group-*/peer-*(incl. named:group-hover/item:),data-*/aria-*/has-*/in-*(these match the element itself:data-[state=open]:is.x[data-state="open"]), responsive breakpoints fromtheme.screens(sm:,md:, ..., plusmin-*/max-*andmin-[900px]:; the defaults are v4's40remto96rem, so they follow the browser's default font size),dark:,motion-safe:/motion-reduce:,print:, capability queries (pointer-coarse:,noscript:,forced-colors:, ...), positional (nth-*,first-line:),not-*, child (*:,**:),starting:, container queries (@container,@container/name,@sm:,@max-md:,@sm/name:,@[400px]:, sizes from--container-*), and arbitrary variants ([&:nth-child(3)]:,[&_p]:,[@media(min-width:900px)]:). - Arbitrary values for nearly every property, with type disambiguation
(
w-[100px],bg-[url(/a.png)],bg-[length:8px],text-[14px]-> font-size vstext-[#fff]-> color,grid-cols-[repeat(3,_1fr)]), including typed hints (text-[color:var(--fg)]). - The v4 CSS-variable shorthand (
w-(--w),text-(length:--s),bg-red-500/(--alpha)), arbitrary properties ([mask-type:luminance],[--x:1px], with variants), and v4 arbitrary-value normalization (w-[calc(100%-2rem)]becomescalc(100% - 2rem),m-[0_auto], andurl()keeps its underscores). - Negatives (
-mt-4), color opacity modifiers (bg-blue-500/50,from-indigo-400/50), and arbitrary spacing multiples (p-13,p-13.5), scaled by the configured--spacingunit. - Animation:
animate-spin|ping|pulse|bounce, theme animations (--animate-*),animate-[wiggle_1s_infinite]andanimate-(--var). Every@keyframesan emitted animation references is output with the stylesheet, as are the@propertyregistrations of the--tw-*composition variables. - Transitions compose like v4:
duration-*andease-*set--tw-durationand--tw-ease, whichtransition,transition-colors, ... read, sotransition-colors duration-700is 0.7s in any order. - Transforms use the individual
translate,rotateandscaleproperties (plustransformfor skew and 3D rotation), so they compose with each other and with keyframe animations such asanimate-spin rotate-45. - Gradients compose like v4 (
bg-linear-*,bg-radial,bg-conic,from-*,via-*,to-*with colors and10%positions, interpolated in oklab; add/oklchetc. to change it). Rings, shadows andinset-ringshare the v4 box-shadow composition, soring-2 ring-offset-2 ring-offset-whitedraws both.space-*anddivide-*style the children through a zero-specificity:where(& > :not(:last-child))selector. - Colors use Tailwind v4's default palette in
oklch()(includingmauve,olive,mistandtaupe), sobg-red-500isoklch(63.7% 0.237 25.331). Opacity modifiers compile tocolor-mix(in oklab, <color> N%, transparent), and@theme --color-*overrides replace any shade. - Filters (
blur-*,brightness-*,grayscale,hue-rotate-*including the negative form,invert,saturate-*,sepia,drop-shadow-*, and everybackdrop-*filter;shadow-*,inset-shadow-*,text-shadow-*anddrop-shadow-*take an opacity such asshadow-xl/20, which like v4 sets the default shadow colour's alpha to 20% and is applied to a shadow colour utility on the same element), animation (animate-*), blend modes, plus layout, typography, interactivity, 3D-transform, border, and background families. - Masks:
mask-none,mask-[...],mask-linear-*,mask-radial-*,mask-conic-*, edge fades (mask-t-from-50%,mask-x-to-transparent, ...), andmask-position|size|repeat|origin|clip|composite|mode|typeutilities compose through--tw-mask-*variables like v4. - Logical properties:
block-*,inline-*,min-/max-block-*,min-/max-inline-*,mbs|mbe|pbs|pbe-*,inset-bs|be-*,border-bs|be-*,scroll-mbs|mbe|pbs|pbe-*. Alsoscrollbar-thin|none|auto,scrollbar-gutter-*,scrollbar-thumb|track-<color>,contain-*,tab-*,transform-fill|border|...(transform-box), the*-safeand*-baselinealignment utilities andw-dvh/h-dvwstyle viewport sizes. outline-hiddenfollows v4:outline-style: none, with a transparent 2px outline under@media (forced-colors: active)(emitted as a nested at-rule inside the utility's rule).- Preflight is Tailwind v4's reset (including
[hidden]staying hidden) and is emitted by default. Settailwind.preflight: falseto opt out. - Scale names follow v4:
rounded-xs|sm|md,shadow-2xs|xs|sm,blur-xs|sm.containerhas amax-widthper configured breakpoint.
#Variant order, stacking, prefix and important
- Stacked variants apply left to right as in Tailwind v4:
hover:before:is.x:hover::beforeand*:hover:is:is(.x > *):hover.hover:is gated by@media (hover: hover). - Rules are emitted in Tailwind's cascade order: utilities without variants
first, then variants by Tailwind's registration order (so
disabled:beatshover:,dark:beats breakpoints, andmax-md:comes beforemax-sm:), breakpoints by size (compared in px acrosspxandrem), and utilities by Tailwind's property order (sopl-4beatspx-2regardless of name). - Class-mode dark mode uses
:where(.dark, .dark *);darkMode: ["class", "[data-mode=dark]"]uses that selector instead of.dark. prefix: "tw"makes utilitiestw:flex/tw:hover:flex; unprefixed utilities are then unknown. CSS variables are not prefixed.important: truemarks every utility!important; a selector string (important: "#app") scopes every utility under it (the Tailwind v3 form). The per-class!works as a prefix (!p-4) or suffix (p-4!).
#Differences from Tailwind
Krate implements Tailwind's utility and variant syntax but is not byte-identical
to the Tailwind CLI. JS plugins and the @tailwindcss/* plugin ecosystem
remain out of scope. Unrecognized classes produce no rule (enable
tailwind.strict to surface them).
Run against every class Tailwind v4.3 can generate, Krate produces a rule for all of them and the computed styles match in Chromium except for these deliberate differences:
- Default theme values are inlined at build time, so the sheet carries no
:rootblock of variables. A default goes live, throughvar(), once the project sets it in a scanned file:.x { --color-blue-600: red },style={{ "--spacing": "2px" }},setProperty("--spacing", ...)or[--spacing:2px]. A default set only from CSS outsidescanDirs(such aspublic/) or from a computed name is not detected; declare it in@themeand it stays live. - Opacity modifiers on colour utilities (
bg-blue-500/50) are emitted ascolor-mix(in oklab, ...)without the precomputedsrgbfallback the Tailwind CLI adds, so browsers withoutcolor-mix()(older than Tailwind v4's supported browsers) get no colour for those utilities. - The
--tw-*composition variables keep inlinevar()fallbacks next to their@propertyregistrations and the@layer propertiesreset.
#Sass, Less and Stylus
Krate has no Sass, Less or Stylus compiler. Importing a .scss, .sass, .less
or .styl file (including .module.scss) is a build error (KR7123) rather
than a page that silently ships without its styles. Compile the file to CSS
first, for example with the sass CLI in a prebuild script
(sass src/styles.scss src/styles.css), and import the .css file, or port the
styles to CSS or Tailwind.
#Invalid CSS
Krate does not rewrite your CSS, but it checks each stylesheet file for
unbalanced braces, an unclosed comment or an unclosed string. A problem is
reported as a warning with the file, line and column
(KR7141). Because the sheets a page imports are
joined into one file, Krate also closes the damage at the end of the file that
caused it (a stray } is dropped, a missing } is added), so a mistake in one
file cannot swallow the rules of the next. Fix the source: the rest of the file
is shipped as written.
#Global CSS & code splitting
Plain CSS imported or referenced in pages is collected per page, in source and
import order, and written as one stylesheet per page to a content-hashed
styles.<hash>.css. Pages whose stylesheets are byte-identical share a single
file, so a layout-only site ships one stylesheet. Rules are never reordered or
moved between files, so the cascade you wrote is the cascade that ships, and
@layer blocks are preserved as authored. See
Contributing -> Architecture for
the full processing steps.
#Custom properties & theming
There's nothing special needed to use CSS custom properties - they pass through
the pipeline unchanged. The docs site uses a :root[data-theme="dark"] scheme
toggled at runtime for light/dark theming.
Last updated: 2026-11-17
Contributors: Noinkin