Recursive AI

Test CSS cascade layer order in C#

onehtml is a free, open-source HTML library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

An @layer list sets priority before selector specificity. Check which color wins without launching a browser.

Terminal
dotnet add package RecursiveAI.OneHtml

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using RecursiveAI.OneHtml;
using RecursiveAI.OneHtml.Css;
 
var doc = Document.Parse("""
    <style>
    @layer base, theme;
    @layer theme { p { color: blue; } }
    @layer base { #note { color: red; } }
    </style>
    <p id="note">Note</p>
    """);
var note = doc.Root.QuerySelector("#note");
var styles = DocumentStyles.Create(doc);
var style = styles.GetStyle(note);
var color = style.GetComputedValue("color");
Console.WriteLine(color);

The example is the full program below: unzip it and dotnet run. To run only the code above, paste it into Program.cs of a new dotnet new console project and dotnet run.

Text
rgb(0, 0, 255)

Blue wins. theme is later in @layer base, theme, even though its block comes first and p is less specific than #note.

Full program

The program keeps the same element and asserts its computed color in four cases. If a color differs, it throws InvalidOperationException with the case name and both values.

C#
using RecursiveAI.OneHtml;
using RecursiveAI.OneHtml.Css;
 
const string html = """
    <style>
    @layer base, theme;
    @layer theme { p { color: blue; } }
    @layer base { #note { color: red; } }
    </style>
    <p id="note">Note</p>
    """;
 
static void Check(string label, string html, string expected)
{
    var doc = Document.Parse(html);
    var note = doc.Root.QuerySelector("#note");
    var style = DocumentStyles.Create(doc).GetStyle(note);
    var actual = style.GetComputedValue("color");
    if (actual != expected)
        throw new InvalidOperationException($"{label}: expected {expected}, got {actual}");
    Console.WriteLine($"{label}: {actual}");
}
 
Check("base, theme", html, "rgb(0, 0, 255)");
Check("theme, base", html.Replace("base, theme", "theme, base"), "rgb(255, 0, 0)");
Check("both important", html.Replace("; }", " !important; }"), "rgb(255, 0, 0)");
Check("unlayered", html.Replace("</style>", "p { color: green; }</style>"), "rgb(0, 128, 0)");
Text
base, theme: rgb(0, 0, 255)
theme, base: rgb(255, 0, 0)
both important: rgb(255, 0, 0)
unlayered: rgb(0, 128, 0)

Variations

Reverse layer priority

In the snippet at the top, replace the order statement inside <style> and leave both rule blocks where they are:

CSS
@layer theme, base;

The color becomes rgb(255, 0, 0) because base now comes last in the list.

Make both declarations important

Keep the original @layer base, theme; statement and replace the two rule blocks:

CSS
@layer theme { p { color: blue !important; } }
@layer base { #note { color: red !important; } }

The color becomes rgb(255, 0, 0) because the earlier layer now wins.

The short answer

Parse HTML with Document.Parse, prepare the cascade with DocumentStyles.Create, then read the target element’s GetComputedValue("color"). For competing normal author rules in different layers, the later layer wins before specificity is compared. The snippet makes that visible by putting a plain p selector in the higher-priority layer and an ID selector in the lower-priority one.

How is CSS layer order determined?

The first appearance of a layer sets its place in the order. A statement such as @layer base, theme; establishes both names before either layer has any rules. Later blocks add declarations to those same layers; opening base again doesn’t move it. If you delete the order statement from the snippet, theme is introduced by its block first and base comes second. Red then wins for normal declarations even though neither selector changed. Put the order statement before the first use of the layer names when you want it to set the order explicitly.

For normal declarations from the same origin, a rule outside any layer beats both named layers. That’s why the full program’s unlayered p rule turns the note green. When tracking down a surprise override, first check whether any matching CSS was left outside @layer, not just which name comes last in the order statement. See CSS Cascade Level 5’s layer ordering rules for the rules across nested layers and style sheets.

Does !important reverse layer order?

Yes, if both declarations are important and come from the same origin, the earlier layer wins. In the full program, base wins over theme in that case. Important layered declarations also beat important unlayered declarations of the same stylesheet origin. If only one matching declaration is important, settle importance before comparing layers. Specificity is still useful when the competing declarations are in the same origin, importance tier, and layer; if those and specificity tie, order of appearance decides.

How do you debug which CSS layer won?

Use the computed value for your assertion. To investigate a failure, print the layer path and selector of the winning declaration. Add this to the snippet at the top, where style is the note’s computed style:

C#
var source = style.GetSource("color");
Console.WriteLine($"{source?.LayerName}: {source?.SelectorText}");
Text
theme: p

If the rules live in a linked stylesheet, give DocumentStyles.Create a StyleSourceOptions.Resolver that supplies its contents. onehtml doesn’t fetch stylesheets; a missing sheet is recorded in Diagnostics and cannot contribute a winning declaration. The cascade docs describe the available style sources and what is computed without layout or painting.

All onehtml recipes