Docs/CSS Frameworks

CSS Frameworks

Unfortunately browsers are rather committed to CSS, so Elegance's job is to let you write the demonic tongue in whichever dialect you prefer and then get out of the way.

When you import a stylesheet from a page or layout and it becomes part of that route's CSS bundle. Everything else: Sass, Less, Stylus, PostCSS, Tailwind, is a transformer in elegance.config.ts.

ExtensionWhat you need
.cssNothing
.module.css(scoped automatically)
.scss, .sasssass
.lessless
.styl, .stylusstylus
.pcss, .postcsspostcss + your plugins

Stylesheet Imports

For plain CSS,i mport a stylesheet from a page, layout, or component.

tsx
// pages/about/page.tsx
import "./about.css";

export default function Page() {
    return <main class="about">...</main>;
}

The build step automatically emits a stylesheet for the route and injects the link into the <head>. If the import lives in a layout, every page under that layout receives it. Layout stylesheets are linked before page stylesheets, so a page can override layout rules at equal specificity.

Imports keep their order, which means import order is cascade order. Import your reset first, then shared styles, then page-specific overrides.

The same works from a component:

tsx
// components/Card.ts
import "./card.css";

export const Card = component({
    view({ children }) {
        return div({ class: "card" }, ...children);
    },
});

Styles imported by a shared component are included in each page that reaches it. CSS is bundled per route rather than split into shared stylesheets the way JS is, so keep truly global styles in a layout and component styles next to their component.

◆

className is accepted as an alias for class in both TSX and Elegance-style elements!

Global styles from `public/`

If you want a stylesheet that is copied verbatim and loaded on every page, put it in public/ and link it yourself:

ts
// pages/docs/layout.ts
export const metadata = () => [
    link({ rel: "stylesheet", href: "/styles/reset.css" }),
];

Files in public/ are not processed by transformers, not bundled, and not content-hashed. Use this for resets, fonts, or a framework's prebuilt CSS that you do not need to customise.

Keep stylesheets under pages/ if you want the dev server to watch them. The file watcher only watches pages/; a CSS file imported from outside that directory still builds, but editing it will not trigger a rebuild until you touch a page file or restart.

The `css` Config

All CSS configuration lives under css in elegance.config.ts:

ts
export const config: EleganceConfig = {
    css: {
        transformers: [],
        modules: {
            enabled: true,
        },
    },
};

transformers is an ordered list of compilers. Each entry has a test regex and a transform function:

ts
type CssTransformer = {
    test: RegExp;
    transform: (source: string, file: string) => string | Promise<string>;
};

The rules are simple:

  • test is matched against the absolute path of the imported file.
  • transform receives the current CSS source and the original file path.
  • It must return CSS, not JavaScript, either directly or as a promise.
  • Every matching transformer runs, in array order. It is not first-match-wins.
  • A later transformer receives the output of the previous one, but its test still sees the original file path.

That last point matters when chaining: a Sass transform followed by an autoprefixer transform should have autoprefixer's test include .scss as well as .css, because the file is still foo.scss even though the source is now plain CSS.

CSS Modules

Any file ending in .module.css or the same pattern with any supported preprocessor extension is treated as a CSS Module. The default export is a map from local class names to generated names:

css
/* components/card.module.css */
.card {
    border: 1px solid #333;
}

.title {
    font-size: 1.5rem;
}
tsx
// components/Card.tsx
import styles from "./card.module.css";

export function Card() {
    return <article class={styles.card}>
        <h2 class={styles.title}>Hello</h2>
    </article>;
}

Generated names look like card_a1b2c3. The suffix is just derived from the file path, so it's stable across builds and identical on the server and client.

CSS Modules are enabled by default. To treat .module.css as an ordinary global stylesheet, turn them off:

ts
css: {
    modules: {
        enabled: false,
    },
},

Custom scoped names

You can override the naming scheme:

ts
import { createHash } from "node:crypto";
import { relative } from "node:path";

css: {
    modules: {
        generateScopedName: (name, file) => {
            const hash = createHash("sha1")
                .update(relative(process.cwd(), file))
                .digest("hex")
                .slice(0, 5);

            return `e_${name}_${hash}`;
        },
    },
},

The generator must be deterministic. The same (name, file, css) triplet is compiled independently for the server and client bundles. If you use a random value, a timestamp, or anything else that changes between runs, the HTML and the hydration bundle will disagree about class names.

Sass, Less, and Stylus

Preprocessors are just transformers. Install the compiler, then return its CSS output.

Sass / SCSS

bash
npm i sass
ts
import sass from "sass";
import { dirname, join } from "node:path";

export const config: EleganceConfig = {
    css: {
        transformers: [
            {
                test: /\.(scss|sass)$/,
                transform: (source, file) =>
                    sass.compileString(source, {
                        loadPaths: [dirname(file), join(process.cwd(), "node_modules")],
                        syntax: file.endsWith(".sass") ? "indented" : "scss",
                    }).css,
            },
        ],
    },
};

The syntax option is required if you want both .scss and indented .sass files to work through the same transformer. compileString is synchronous and returns { css }.

Less

bash
npm i less
ts
import less from "less";
import { dirname, join } from "node:path";

{
    test: /\.less$/,
    transform: (source, file) =>
        less.render(source, {
            paths: [dirname(file), join(process.cwd(), "node_modules")],
            filename: file,
        }).then((out) => out.css),
}

filename is not optional in practice: Less uses it for relative imports and error messages.

Stylus

bash
npm i stylus
ts
import stylus from "stylus";
import { dirname, join } from "node:path";

{
    test: /\.styl(us)?$/,
    transform: (source, file) =>
        new Promise<string>((resolve, reject) => {
            stylus(source)
                .set("filename", file)
                .set("paths", [dirname(file), join(process.cwd(), "node_modules")])
                .render((err, css) => (err ? reject(err) : resolve(css)));
        }),
}

Stylus has a callback API, so the promise wrapper is doing the work of making it fit the transformer contract.

PostCSS

PostCSS is the usual home for autoprefixer, nesting, and other CSS-to-CSS plugins. Its JS API does not read postcss.config.js for you, so pass the plugins explicitly:

bash
npm i postcss autoprefixer postcss-nested
ts
import postcss from "postcss";
import autoprefixer from "autoprefixer";
import postcssNested from "postcss-nested";

{
    test: /\.(css|pcss|postcss)$/,
    transform: (source, file) =>
        postcss([postcssNested(), autoprefixer()])
            .process(source, { from: file })
            .then((result) => result.css),
}

Always pass from. PostCSS uses it to resolve relative paths, generate source maps, and report useful warnings.

If you already have a PostCSS config you want to reuse, load it yourself (for example with postcss-load-config) and pass the resulting plugins to postcss(). There is no implicit config discovery.

Tailwind CSS

Tailwind is a PostCSS plugin, so it slots into the same css.transformers list. The setup differs between v4 and v3.

Tailwind v4

bash
npm i tailwindcss @tailwindcss/postcss postcss

Create a stylesheet with the Tailwind import:

css
/* pages/styles/tailwind.css */
@import "tailwindcss";

Then run it through PostCSS:

ts
import postcss from "postcss";
import tailwindcss from "@tailwindcss/postcss";

export const config: EleganceConfig = {
    css: {
        transformers: [
            {
                test: /\.css$/,
                transform: (source, file) =>
                    postcss([tailwindcss()])
                        .process(source, { from: file })
                        .then((result) => result.css),
            },
        ],
    },
};

Import the stylesheet from a layout so every page gets it:

tsx
// pages/layout.ts
import "./styles/tailwind.css";

Tailwind v4 detects source files automatically. from gives the plugin its base directory, and the scan respects .gitignore. If your pages live outside the detected tree, add an explicit source in the stylesheet. Paths are relative to the CSS file:

css
@import "tailwindcss";

/* from pages/styles/, this points at pages/ */
@source "../../pages";

No tailwind.config.js is required. Theme customisation happens in CSS with @theme.

Tailwind v3

bash
npm i tailwindcss@3 postcss autoprefixer
ts
import postcss from "postcss";
import tailwindcss from "tailwindcss";
import autoprefixer from "autoprefixer";

{
    test: /\.css$/,
    transform: (source, file) =>
        postcss([tailwindcss(), autoprefixer()])
            .process(source, { from: file })
            .then((result) => result.css),
}

Tailwind v3 needs a config with a content list and the directives in your stylesheet:

ts
// tailwind.config.ts
export default {
    content: ["./pages/**/*.{ts,tsx}"],
    theme: {
        extend: {},
    },
    plugins: [],
};
css
@tailwind base;
@tailwind components;
@tailwind utilities;

Include both .ts and .tsx in content. Components written in .ts files are just as capable of containing class strings, and a .tsx-only glob will silently miss them. If components live outside pages/, add those directories too.

Content scanning

Both versions only generate utilities for class names they can find as complete strings. This works:

tsx
div({ class: isActive ? "text-amber-400" : "text-neutral-500" });

This does not:

tsx
div({ class: `text-${color}-400` });

Tailwind cannot see text-amber-400 in the second example, so it will not generate it. Keep full class names in the source, or use a safelist / @source inline(...) where the version supports it.

Prebuilt Framework CSS

Frameworks like Bootstrap and Bulma ship a ready-made stylesheet. Imports from node_modules are externalized by default, so the CSS bundler never sees them. A package stylesheet will not be included in the route's CSS, and importing it directly can fail when the server tries to load it.

The simple and reliable approach is to copy the stylesheet into your own tree. For example: pages/styles/, and import it:

tsx
// pages/layout.ts
import "./styles/bootstrap.min.css";

Or put it in public/ and link it from metadata, exactly like any other static stylesheet:

ts
export const metadata = () => [
    link({ rel: "stylesheet", href: "/vendor/bootstrap.min.css" }),
];

A package can opt into bundling by declaring an elegance field in its package.json, but most third-party CSS frameworks do not. Copying the file is boring, predictable, and works today.

Chaining Transformers

Transformers are applied in the order they appear. A typical Sass + PostCSS + autoprefixer chain looks like this:

ts
transformers: [
    {
        test: /\.(scss|sass)$/,
        transform: sassTransform,
    },
    {
        test: /\.(css|scss|sass)$/,
        transform: postcssNestedTransform,
    },
    {
        test: /\.(css|scss|sass)$/,
        transform: autoprefixerTransform,
    },
],

Two rules keep chains predictable:

  • Put syntax compilers first. PostCSS plugins expect CSS, not SCSS.
  • Make every later test match the original extensions. The file path does not change when Sass turns foo.scss into CSS, so autoprefixer needs /\.(css|scss|sass)$/ to see it.

Autoprefixer belongs last. Nesting and custom-property transforms should run before it so it sees the final declarations.

Output and Caching

For every route, Elegance writes the CSS associated with its layouts and its page into stylesheets under /css/. The link tags are added to <head> in this order:

  1. Layout stylesheets, outermost layout first.
  2. The page's own stylesheet.

That ordering is the cascade you want: shared foundations first, page-specific overrides last.

CSS Modules names are deterministic per file, so they survive rebuilds and match between the server-rendered HTML and the client bundle. Plain CSS is global; if two files define .card, the later one wins at equal specificity.

The dev server watches pages/ and rebuilds on change. elegance.config.ts is loaded once at startup, so restart the server after changing transformers or module settings.

Troubleshooting

`No loader is configured for ".scss"`: the transformer's test did not match the file, or the transformer was added after the server started. Check the regex and restart.

Styles are missing from the page: plain stylesheet imports are injected automatically; public/ files are not. If the file lives in public/, add a link in metadata.

Tailwind generates no utilities: check the content globs (v3) or the @source paths (v4). Also check that the classes are complete strings in the source.

Class names differ between HTML and client: a custom generateScopedName is not deterministic. Derive the name from name, file, and/or css, never from time or randomness.

Package CSS is ignored: imports from node_modules are externalized by default. Copy the stylesheet into your own tree, or put it in public/.

A later transformer never runs: its test only matches the compiled extension. Match the original extension instead, as described in Chaining Transformers.