Configuration
Class Merge
How twblazor merges conflicting Tailwind classes so the last one wins, and how to turn it off or add your own utilities with TwBlazorOptions.ClassMerge.
Last updated
Overview
class attribute from its theme classes, then your own Class. When two of those classes set the same CSS property, such as px-4 from the theme and px-2 from you, the one added last wins and the other is removed. Without merging, both would reach the element and the order of Tailwind's stylesheet, not your intent, would decide the result.
It is built into twblazor, so there is nothing to install and nothing to set up. ClassBuilder.Build() does the merge for every component. The sections below show the rules it follows, and every result in them is produced by ClassBuilder when this page renders, so it is always what the library really does.
The rules are those of the tailwind-merge npm package for Tailwind CSS v4. Its class groups are generated into twblazor from that package, and twblazor's tests compare the two on several hundred class strings. See Differences from tailwind-merge for the two places they part.
<TwButton Label="Compact" Class="px-2" />
@* Renders px-2 and no px-6. The colors, height and the rest of the theme are untouched. *@Last conflicting class wins
The classes do not need to be next to each other, and several conflicts are resolved in the same pass.
new ClassBuilder("p-5 p-2 p-4").Build(); // → "p-4"
new ClassBuilder("flex px-4 items-center px-2").Build(); // → "flex items-center px-2"
new ClassBuilder("text-sm font-bold text-lg font-normal").Build();
// → "text-lg font-normal"Allows refinements
p-3 sets several sides at once, and a class for one of those sides, such as px-5, is more specific. When the more specific class comes after the shorthand it refines it, so both are kept: padding everywhere, then a different horizontal padding.
The order decides it. The other way round, the shorthand comes last and covers everything the specific class set, so the specific class is removed.
new ClassBuilder("p-3 px-5").Build(); // → "p-3 px-5"
new ClassBuilder("px-5 p-3").Build(); // → "p-3"
new ClassBuilder("inset-x-4 right-4").Build(); // → "inset-x-4 right-4"
new ClassBuilder("rounded-lg rounded-t-none").Build(); // → "rounded-lg rounded-t-none"
new ClassBuilder("rounded-t-none rounded-lg").Build(); // → "rounded-lg"
new ClassBuilder("border-2 border-t-4").Build(); // → "border-2 border-t-4"Resolves non-trivial conflicts
- A shorthand and the classes it covers:
pwithpx,pyand each side, and the same for margin, inset, gap, overflow, border width, border color, rounded corners and scroll margin and padding. size-8sets both width and height, so it replaces an earlierw-4andh-6.flex-1sets grow, shrink and basis, so it replaces earliergrow,shrinkandbasis-4.line-clamp-1sets display and overflow, so it replaces earlier classes for those.- Every display value conflicts with every other, as do the position values (
static,relative,absolute) and the text decorations (underline,line-through). - A negative value conflicts with the positive class for the same property.
new ClassBuilder("inset-x-px -inset-1").Build(); // → "-inset-1"
new ClassBuilder("bottom-auto inset-y-6").Build(); // → "inset-y-6"
new ClassBuilder("inline block").Build(); // → "block"
new ClassBuilder("w-4 h-6 size-8").Build(); // → "size-8"
new ClassBuilder("basis-4 grow flex-1").Build(); // → "flex-1"
new ClassBuilder("overflow-auto inline line-clamp-1").Build(); // → "line-clamp-1"Supports modifiers and stacked modifiers
hover:p-4 never removes p-2, and md:p-4 never removes lg:p-6. This holds for every kind of modifier: state (hover, focus, disabled), responsive (md, max-lg), color scheme (dark), group and peer (group-hover, peer-checked), and data and aria attributes.
When modifiers are stacked their order does not matter, so hover:focus: and focus:hover: are the same thing.
new ClassBuilder("p-2 hover:p-4").Build(); // → "p-2 hover:p-4"
new ClassBuilder("hover:p-2 hover:p-4").Build(); // → "hover:p-4"
new ClassBuilder("hover:focus:p-2 focus:hover:p-4").Build(); // → "focus:hover:p-4"
new ClassBuilder("md:p-2 md:p-4 lg:p-6").Build(); // → "md:p-4 lg:p-6"
new ClassBuilder("dark:hover:bg-red-500 hover:dark:bg-blue-500").Build();
// → "hover:dark:bg-blue-500"
new ClassBuilder("group-hover:p-1 peer-hover:p-2 group-hover:p-3").Build();
// → "peer-hover:p-2 group-hover:p-3"Where the order does matter
Some modifiers change which element is styled: before, after, placeholder, file, marker, selection, first-line, first-letter, backdrop, details-content, * and **, and any arbitrary variant. Moving another modifier from one side of these to the other changes the CSS Tailwind produces, so before:hover:p-1 and hover:before:p-2 are treated as different and both are kept. If you define such a variant yourself with @custom-variant, add its name to OrderSensitiveVariants so it is treated the same way.
new ClassBuilder("before:hover:p-1 hover:before:p-2").Build();
// → "before:hover:p-1 hover:before:p-2"
new ClassBuilder("hover:before:p-1 hover:before:p-2").Build(); // → "hover:before:p-2"Supports a Tailwind prefix
tw:px-4 or tw:hover:px-4. Prefixed classes are merged with no configuration, and everything on this page applies to them: refinements, modifiers, arbitrary values and the important modifier.
A prefixed class never conflicts with the unprefixed class of the same name. The two come from different stylesheets, so neither can stand in for the other.
new ClassBuilder("tw:px-4 tw:px-2").Build(); // → "tw:px-2"
new ClassBuilder("tw:pt-1 tw:py-3").Build(); // → "tw:py-3"
new ClassBuilder("tw:hover:px-4 tw:hover:px-2").Build(); // → "tw:hover:px-2"
new ClassBuilder("tw:px-4 px-2").Build(); // → "tw:px-4 px-2"
By default unprefixed classes are merged as well, which is right when the page mixes a prefixed and an unprefixed Tailwind build. If your whole application is prefixed, set Prefix to the value you gave prefix(...) in your stylesheet. Only classes that start with it are then treated as Tailwind utilities. Any other class, such as a hidden or container that belongs to another framework on the page, is left alone.
// app.css: @import "tailwindcss" prefix(tw);
builder.Services.AddTwBlazor(options => options.ClassMerge.Prefix = "tw", Theme.CreateTheme);
// "tw:px-4 tw:px-2" renders as "tw:px-2".
// "hidden block" is left as it is: without the prefix they are not Tailwind classes.Supports arbitrary values
m-[10px], and the Tailwind v4 shorthand for a CSS variable, w-(--sidebar). An arbitrary value conflicts with the named values for the same property, in either order.
new ClassBuilder("m-[2px] m-[10px]").Build(); // → "m-[10px]"
new ClassBuilder("text-[14px] text-sm").Build(); // → "text-sm"
new ClassBuilder("w-(--sidebar) w-64").Build(); // → "w-64"
new ClassBuilder("bg-black bg-(--my-color) bg-[color:var(--mystery-var)]").Build();
// → "bg-[color:var(--mystery-var)]"
new ClassBuilder("grid-cols-[1fr,auto] grid-cols-2").Build(); // → "grid-cols-2"Labels are necessary in ambiguous cases
A class like text-[calc(var(--rebecca)-1rem)] could be a font size or a text color, so the value is inspected for clues such as calc() or a number followed by a unit like 1rem. When the type can't be told from the value, as in text-[theme(myCustomScale.rebecca)], it is treated as a color. Add a CSS data type label, as Tailwind itself does, to say which one you mean: text-[length:theme(myCustomScale.rebecca)].
A variable in the shorthand form can never be inspected, so text-(--my-size) is always read as a color. Label it when it is something else: text-(length:--my-size). The labels are length, size, position, percentage, image, url, number, weight, family-name and shadow.
new ClassBuilder("text-2xl text-(--my-color)").Build(); // → "text-2xl text-(--my-color)"
new ClassBuilder("text-2xl text-(length:--my-size)").Build();
// → "text-(length:--my-size)"Supports arbitrary properties
[mask-type:alpha], conflicts with another arbitrary property that has the same property name. CSS variables set this way work the same, so a later [--scroll-offset:44px] replaces an earlier one. Modifiers apply as they do everywhere else: the two only conflict when their modifiers match.
new ClassBuilder("[mask-type:luminance] [mask-type:alpha]").Build();
// → "[mask-type:alpha]"
new ClassBuilder("hover:[color:red] hover:[color:blue]").Build(); // → "hover:[color:blue]"
new ClassBuilder("[--scroll-offset:56px] lg:[--scroll-offset:44px]").Build();
// → "[--scroll-offset:56px] lg:[--scroll-offset:44px]"[padding:1rem] p-8 and expect one of them to go.
Supports arbitrary variants
[&>*]: or [&:nth-child(3)]:, are modifiers like any other: two classes conflict when they have the same one. The selector is compared as written, so [&>*]: and [&>p]: are different.
Like arbitrary properties, an arbitrary variant is never matched against a predefined modifier, so [&:focus]:ring and focus:ring-4 are both kept. And because an arbitrary variant can change which element is styled, the order of the modifiers around it is kept too.
new ClassBuilder("[&:nth-child(3)]:py-0 [&:nth-child(3)]:py-4").Build();
// → "[&:nth-child(3)]:py-4"
new ClassBuilder("[&>*]:underline [&>*]:line-through").Build(); // → "[&>*]:line-through"
new ClassBuilder("[&>*]:p-1 [&>p]:p-2").Build(); // → "[&>*]:p-1 [&>p]:p-2"
new ClassBuilder("[&:focus]:ring focus:ring-4").Build(); // → "[&:focus]:ring focus:ring-4"
new ClassBuilder("hover:[&>*]:p-1 [&>*]:hover:p-2").Build();
// → "hover:[&>*]:p-1 [&>*]:hover:p-2"Supports important modifier
The modifier can be written after the class, p-4!, which is the Tailwind v4 form, or before it, !p-4, which is the older form Tailwind still accepts. The two forms conflict with each other, and both work with modifiers.
new ClassBuilder("p-3! p-4! p-5").Build(); // → "p-4! p-5"
new ClassBuilder("right-2! -inset-x-1!").Build(); // → "-inset-x-1!"
new ClassBuilder("!p-3 p-4!").Build(); // → "p-4!"
new ClassBuilder("hover:p-3! hover:p-4!").Build(); // → "hover:p-4!"
new ClassBuilder("p-3 p-4!").Build(); // → "p-3 p-4!"Supports postfix modifiers
text-lg/7 it sets the line height as well as the font size, so the class also replaces an earlier leading-6. A leading class written after it refines it and is kept.
Elsewhere the modifier is an opacity, as in bg-red-500/50, and does not change what the class conflicts with. A slash that is part of the value, as in the fraction w-1/2, is not a modifier at all.
new ClassBuilder("text-sm leading-6 text-lg/7").Build(); // → "text-lg/7"
new ClassBuilder("text-lg/7 leading-9").Build(); // → "text-lg/7 leading-9"
new ClassBuilder("bg-red-500/50 bg-blue-500").Build(); // → "bg-blue-500"
new ClassBuilder("w-full w-1/2").Build(); // → "w-1/2"Preserves non-Tailwind classes
A class counts as a Tailwind utility only when its value is one Tailwind has. w-half starts like a width, but half is not a width Tailwind knows, so it is left alone and does not remove w-1/2.
new ClassBuilder("p-5 p-2 my-non-tailwind-class p-4").Build();
// → "my-non-tailwind-class p-4"
new ClassBuilder("btn btn-primary btn").Build(); // → "btn btn-primary btn"
new ClassBuilder("w-1/2 w-half").Build(); // → "w-1/2 w-half"Supports custom colors out of the box
new ClassBuilder("text-red text-secret-sauce").Build(); // → "text-secret-sauce"
new ClassBuilder("bg-brand bg-brand-dark").Build(); // → "bg-brand-dark"
new ClassBuilder("ring-brand ring-2 ring-other").Build(); // → "ring-2 ring-other"
new ClassBuilder("font-sans font-my-family").Build(); // → "font-my-family"Custom sizes need a group
The same rule means a custom name that is not a color is misread. With --text-huge in your theme, text-huge is taken for a color and will not replace text-sm, and a custom radius such as rounded-brand is not recognised at all. Sizes named like Tailwind's own, such as text-3.5xl, are fine. For any other name, add the class to the built-in group it belongs to, as shown under Add your own utilities.
Composition
ClassBuilder merges once, when you call Build(), so you can add classes in as many calls as you like. The order of the calls is the order of the classes, which is why a component adds its theme classes first and your Class last. A conditional class takes part in the merge only when its condition is true.
Whitespace is tidied on the way: extra spaces, tabs and line breaks become single spaces, and a null or empty string adds nothing.
var classes = new ClassBuilder("some-class")
.AddClass("another-class yet-another-class")
.AddClass("so-many-classes")
.Build();
// → "some-class another-class yet-another-class so-many-classes"
var compact = true;
var button = new ClassBuilder("px-6 py-2")
.AddClass("px-2", compact)
.Build();
// → "py-2 px-2"Configuration
ClassMerge alone and everything above applies. To change it, set it on the options you pass to AddTwBlazor. It is part of TwBlazorOptions, not the theme, and applies to your whole application.
The configuration is read once, when AddTwBlazor runs, so set it there and not later. These are the settings:
Enabledturns merging on or off. It is on by default.Prefixis the prefix of your Tailwind build, such astw. Classes without it are then left alone.Groupsholds your own class groups, for utilities the merge does not know.OrderSensitiveVariantsnames custom variants whose position among the other variants matters.CacheSizeis how many results are remembered. It is 2,048 by default, and 0 turns the cache off.
builder.Services.AddTwBlazor(options =>
{
options.ClassMerge.Enabled = true; // the default
options.ClassMerge.Prefix = "tw"; // only for a prefixed Tailwind build
options.ClassMerge.CacheSize = 4096; // 2,048 by default
options.ClassMerge.Groups.Add(new TwClassGroup("btn-size", ["btn"]));
options.ClassMerge.OrderSensitiveVariants.Add("scrollbar");
}, Theme.CreateTheme);Turn it off
With Enabled set to false every class is rendered exactly as written, with only the surrounding whitespace trimmed. Both the theme's class and yours then reach the element, and which one applies is decided by their order in Tailwind's stylesheet. Turn it off only if you resolve conflicts some other way.
builder.Services.AddTwBlazor(options => options.ClassMerge.Enabled = false, Theme.CreateTheme);Add your own utilities
A TwClassGroup is a set of classes that conflict with each other. A class belongs to the group when it equals one of its prefixes or starts with the prefix and a dash, so the prefix btn matches btn, btn-sm and btn-lg, and does not match btns. Use it for classes you define with @utility or in your own CSS. Custom groups are checked before the built-in ones.
Classes in a custom group get the same treatment as Tailwind's: modifiers, the important modifier, a leading minus and a postfix modifier are all understood, so hover:btn-sm only conflicts with hover:btn-lg.
// Of btn, btn-sm and btn-lg only the last one added is kept.
options.ClassMerge.Groups.Add(new TwClassGroup("btn-size", ["btn"]));
// "btn-sm btn-lg flex" renders as "btn-lg flex".Give a group the name of a built-in one to add your classes to it. This is how to teach the merge a custom size from your Tailwind theme: the class then conflicts with everything else in that group and inherits what the group overrides.
// text-huge comes from --text-huge in your Tailwind theme. In the font-size group it
// replaces text-sm, and an earlier leading-6, the way a built-in font size does.
options.ClassMerge.Groups.Add(new TwClassGroup("font-size", []) { Classes = ["text-huge"] });
// rounded-brand comes from --radius-brand.
options.ClassMerge.Groups.Add(new TwClassGroup("rounded", []) { Classes = ["rounded-brand"] });
// "text-sm leading-6 text-huge" renders as "text-huge".
// "rounded-md rounded-brand" renders as "rounded-brand".Classes matches a class by its whole name, where a prefix would also match everything that starts with it. Use it for a single class such as text-huge, so that an unrelated text-huge-wide is not pulled into the group. A group can have prefixes, classes or both.
Override other groups
Set Overrides to the names of groups that a later class from this one also removes. It works in one direction, like Tailwind's own shorthands: a later pad-4 removes an earlier px-2, and a later px-2 refines an earlier pad-4, so both are kept.
Reusing the name of a built-in group, such as p, adds your classes to that group and keeps its existing overrides. The built-in groups are named as in tailwind-merge. The common ones are p, px, py, m, w, h, size, display, font-size, font-weight, font-family, leading, text-color, bg-color, border-w, border-color, rounded, shadow and shadow-color.
// A later pad-4 also removes earlier px and py classes.
options.ClassMerge.Groups.Add(new TwClassGroup("spacing-all", ["pad"])
{
Overrides = ["px", "py"],
});
// Add gutter-* to the built-in padding group instead.
options.ClassMerge.Groups.Add(new TwClassGroup("p", ["gutter"]));ModifierOverrides does the same, but only for a class written with a postfix modifier. This is how the built-in font sizes work: text-lg/7 removes an earlier line height and text-lg does not. Use it when the part after the slash in your own utility sets a second property.
// tile-2/50 sets an opacity as well, so it removes an earlier opacity-75. tile-2 does not.
options.ClassMerge.Groups.Add(new TwClassGroup("tile", ["tile"])
{
ModifierOverrides = ["opacity"],
});What it does not do
- It does not compare an arbitrary property with the utility for the same property, so
[padding:1rem] p-8keeps both. - It does not remove duplicates of classes that are not Tailwind utilities.
- It does not reorder classes. What is kept stays where it was written.
- It does not know your own utilities or custom size names until you add a group for them.
- It does not read your Tailwind configuration, so it cannot tell whether a class exists in your build.
Differences from tailwind-merge
-
An unlabelled arbitrary background value made of position keywords, such as
bg-[right_0.5rem_center], is a background position, as it is to Tailwind. tailwind-merge reads it as a color unless you writebg-[position:right_0.5rem_center]. -
A line height modifier is recognised after the older important syntax too, so
!text-sm/6replaces an earlier!leading-4just astext-sm/6!does.
new ClassBuilder("bg-red-500 bg-[right_0.5rem_center]").Build();
// → "bg-red-500 bg-[right_0.5rem_center]"
new ClassBuilder("!leading-4 !text-sm/6").Build(); // → "!text-sm/6"
Configuration differs too. tailwind-merge is extended with extendTailwindMerge and its own config format. twblazor has the settings listed under Configuration, set in C#. Its Prefix behaves like tailwind-merge's prefix, and Groups, Overrides and ModifierOverrides cover what classGroups, conflictingClassGroups and conflictingClassGroupModifiers do there.
Performance
Build() and holds up to 2,048 different results before it starts again. Change that number with CacheSize if your application builds far more distinct class strings than that, or set it to 0 to always merge afresh. A component that renders with the same classes as last time gets its answer from one dictionary lookup.