---
title: "Validate CSS declarations with custom rules in C#"
url: https://recursiveai.org/onehtml/cookbook/validate-css-declarations-with-custom-rules/
description: "Use a custom CSS declaration validator in C# to reject a width your host doesn’t support and let the earlier width declaration win."
version: "1.6.0"
---

# Validate CSS declarations with custom rules in C#

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

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneHtml) · [GitHub](https://github.com/recursive-ai-oss/onehtml-csharp) · [Docs](https://recursiveai.org/onehtml/docs/) · [Download example (.zip)](https://recursiveai.org/onehtml/cookbook/validate-css-declarations-with-custom-rules/validate-css-declarations-with-custom-rules.zip)

A declaration pairs a CSS property with a value. Reject a value your layout engine doesn’t handle before onehtml chooses which declaration wins.

```shell
dotnet add package RecursiveAI.OneHtml
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using RecursiveAI.OneHtml;
using RecursiveAI.OneHtml.Css;
var doc = Document.Parse("""
    <style>p { width: 100%;
      width: -webkit-fill-available;
    }</style><p id="card">Card</p>
    """);
var styles = DocumentStyles.Create(doc,
    options: new StyleSourceOptions {
        DeclarationValidator =
            (name, value, _) =>
                !(name == "width" &&
                  value.IsIdent(value.From,
                      "-webkit-fill-available") &&
                  value.Next(value.From)
                      == value.To)
    });
var node = doc.GetElementById("card");
Console.WriteLine(styles.GetStyle(node)
    .GetPropertyValue("width"));
```

Unzip [the example](https://recursiveai.org/onehtml/cookbook/validate-css-declarations-with-custom-rules/validate-css-declarations-with-custom-rules.zip), then `dotnet run`.

The snippet prints the winning CSS value, not a pixel measurement:

```text
100%
```

`IsIdent` checks the first token for `-webkit-fill-available`; `Next` checks that no other token follows it.

## The full program

The download computes the same element’s width without the callback, then with it.

```csharp
using RecursiveAI.OneHtml;
using RecursiveAI.OneHtml.Css;

var doc = Document.Parse("""
    <style>p {
      width: 100%;
      width: -webkit-fill-available;
    }</style>
    <p id="card">Card</p>
    """);
var options = new StyleSourceOptions
{
    DeclarationValidator = (name, v, _) =>
        !(name == "width" &&
          v.IsIdent(v.From,
              "-webkit-fill-available") &&
          v.Next(v.From) == v.To)
};
var node = doc.GetElementById("card");
var baseline = DocumentStyles.Create(doc);
var styles = DocumentStyles.Create(
    doc, options: options);
Console.WriteLine(baseline.GetStyle(node)
    .GetPropertyValue("width"));
Console.WriteLine(styles.GetStyle(node)
    .GetPropertyValue("width"));
```

```text
-webkit-fill-available
100%
```

If the callback rejects a declaration and no other declaration wins, the inherited or initial value applies as appropriate for the property.

## Variations

**Reject an important declaration.** Replace just the second declaration in the HTML with the line below; the download still prints `-webkit-fill-available` and then `100%`. A rejected declaration never enters the cascade, even with `!important`.

```css
width: -webkit-fill-available !important;
```

**Apply the rule only to author CSS.** In the full program, replace the callback with this one. The inline stylesheet is an author stylesheet, so the output is unchanged. The callback now accepts declarations from other origins, such as a user stylesheet.

```csharp
DeclarationValidator = (name, v, origin) =>
    !(origin == StyleOrigin.Author &&
      name == "width" &&
      v.IsIdent(v.From, "-webkit-fill-available") &&
      v.Next(v.From) == v.To)
```

## Related recipes

- [Compute an element’s CSS styles](https://recursiveai.org/onehtml/cookbook/computed-style-csharp/)
- [Check a CSS `@supports` condition](https://recursiveai.org/onehtml/cookbook/check-css-supports-condition/)
- [Resolve CSS custom properties with fallbacks](https://recursiveai.org/onehtml/cookbook/resolve-css-custom-properties-with-fallback/)

## The short answer

Set `StyleSourceOptions.DeclarationValidator` when you call `DocumentStyles.Create`. Return `false` for a declaration your own CSS consumer can’t handle. Onehtml treats it as if it didn’t parse, so the earlier `width: 100%` can win. This is a way to add the grammar rules of the software consuming the styles, not a general stylesheet syntax checker.

## How can I validate CSS property values before they apply?

Onehtml already parses CSS and applies the rules it knows for typed properties and supported shorthands. The [declaration validator](https://recursiveai.org/onehtml/docs/cascade/#declaration-validators) adds checks for values that pass those built-in rules but that your host doesn’t accept. It gets the property name, a `TokenRange` for the value, and the origin of the declaration. The range excludes surrounding whitespace.

The callback is used for eligible author and user declarations, including declarations in style attributes. It doesn’t override built-in typed parsers, and it doesn’t run for custom properties, CSS-wide keywords such as `initial`, or the library’s own default stylesheet and presentational hints. For shorthands the library expands, it checks the resulting untyped longhands; if one is rejected, the whole shorthand is dropped. Keep the callback deterministic and thread-safe: the library may validate the same rule on two threads when it is first used.

## Why does an invalid CSS value sometimes override its fallback?

It depends on **when** the value fails. If you reject a declaration when onehtml collects the candidates for the cascade, that declaration cannot win. The earlier `width: 100%` in this example remains a candidate.

A value that only becomes invalid after `var()` substitution is different. The winner has already been chosen when substitution happens. The validator sees neither the declaration containing `var()` nor the substituted value, and onehtml does not go back and choose the previous declaration. The invalid value behaves as `unset`; see [how the cascade resolves variables](https://recursiveai.org/onehtml/docs/cascade/#cascade). A fallback inside `var()` is for an absent or invalid variable, not for a replacement that the consuming property rejects.
