FluentCss documentation

How it works

FluentCss turns method calls into utility classes, collects them in a registry and emits a single stylesheet.

The pipeline

  1. 1. You call a fluent method such as .Background(Color.Red500).
  2. 2. A UtilityClass is created: a CSS property, a value and a generated class name.
  3. 3. The class is added to a ClassRegistry. Duplicates are ignored.
  4. 4. The registry appends the CSS rule and invalidates its cached output.
  5. 5. ToString() on the builder returns the class names for your markup.

A utility class

Every call produces one utility. The builder keeps the class names in order, so the string returned by ToString() matches the order in which you composed it.

var button = FluentCssBuilder.Css
    .Background(Color.Blue500)
    .Color(Color.White)
    .Px(6)
    .Py(3)
    .RoundedMd();

string classes = button.ToString();
// bg-blue-500 text-white px-6 py-3 rounded-md

Class name format

A generated class name is assembled from the active variants, in this order:

[media]:[theme]:[pseudo]:utility

Utility Generated CSS
bg-red-500 no variant
hover:bg-red-600 pseudo state
theme-dark:text-white theme (dark mode)
min-md:flex media query
theme-dark:hover:bg-slate-700 theme and pseudo
min-md:theme-dark:focus:opacity-0 media, theme and pseudo

The same information drives the selector. Variant prefixes are escaped with a backslash so the colon can appear inside a CSS class name.

.bg-blue-500 { background-color: oklch(0.623 0.214 259.815) }
.text-white { color: #fff }
.px-6 { padding-inline: 1.5rem }
.py-3 { padding-block: 0.75rem }
.rounded-md { border-radius: 0.375rem }

/* variants are escaped and scoped */
.hover\:bg-blue-600:hover { background-color: oklch(0.546 0.245 262.881) }
@media (width > 48rem) { .min-md\:flex { display: flex } }
.theme-dark .theme-dark\:text-white { color: #fff }

The registry

ClassRegistry.DefaultRegistry is a process wide collection. Because a utility is only added once, calling the same method from several components produces a single CSS rule. The registry also exposes the final output:

// Add through the builder (recommended)
FluentCssBuilder.Css.Background(Color.Red500);

// Read the generated stylesheet
string css = ClassRegistry.DefaultRegistry.Css;

// UTF-8 bytes, handy for writing a file or streaming
byte[] bytes = ClassRegistry.DefaultRegistry.CssUtf8;

Rendering in Blazor

The CssStyles component subscribes to OnClassAdded. In an interactive render mode it re-renders as new classes appear. In static server rendering it reads the registry once, after the page has finished rendering, which is why it belongs at the end of the layout.

Now that you know the mechanics, learn how to style with utility classes.