---
title: "Restyle CSS after a DOM edit in C#"
url: https://recursiveai.org/onehtml/cookbook/incrementally-restyle-after-dom-edit/
description: "Edit an HTML element in C#, update the computed styles affected by the edit, and compare the result of a CSS :has() rule with a fresh cascade."
version: "1.6.0"
---

# Restyle CSS after a DOM edit 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/incrementally-restyle-after-dom-edit/incrementally-restyle-after-dom-edit.zip)

After a local HTML edit, `Restyle` recomputes styles only for the elements the edit affects, not the whole document.

```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;
using RecursiveAI.OneHtml.Editing;

var doc = Document.Parse(
    File.ReadAllText("sample.html"));
var styles = DocumentStyles.Create(doc);
styles.ComputeAll();
var badge = doc.GetElementById("badge");
var edit = doc.Apply([
    Edit.SetAttribute(badge, "class", "late")
]);
var updated = edit.Document
    ?? throw new Exception("Edit failed");
var result = styles.Restyle(edit);
var card = updated.GetElementById("card");
var style = result.Styles.GetStyle(card);
var color = style.GetComputedValue("color");
Console.WriteLine(color);
```

Unzip [the example](https://recursiveai.org/onehtml/cookbook/incrementally-restyle-after-dom-edit/incrementally-restyle-after-dom-edit.zip), then `dotnet run`.

With `sample.html` from the download, adding `late` to the badge makes its parent card red:

```text
rgb(255, 0, 0)
```

The `sample.html` file in the download contains:

```html
<!doctype html>
<style>
#card { color: blue }
#card:has(> .late) { color: red }
</style>
<div id=card><span id=badge>Due</span></div>
<p id=note>Unrelated note</p>
```

## The full program

Each successful edit returns a new document, so use the edit’s map to find the corresponding nodes in the new document. This `Program.cs` looks up those nodes by ID instead, then compares their colors with styles computed from scratch.

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

var doc = Document.Parse(File.ReadAllText("sample.html"));
var before = DocumentStyles.Create(doc);
before.ComputeAll();
var badge = doc.GetElementById("badge");
var edit = doc.Apply([Edit.SetAttribute(badge, "class", "late")]);
if (!edit.Succeeded || edit.Document is not { } updated)
    throw new InvalidOperationException("Could not edit badge.");

var restyle = before.Restyle(edit);
var fresh = DocumentStyles.Create(updated);
foreach (var id in new[] { "card", "badge", "note" })
{
    var oldNode = doc.GetElementById(id);
    var newNode = updated.GetElementById(id);
    var oldColor = before.GetStyle(oldNode).GetComputedValue("color");
    var newColor = restyle.Styles.GetStyle(newNode).GetComputedValue("color");
    var freshColor = fresh.GetStyle(newNode).GetComputedValue("color");
    if (newColor != freshColor)
        throw new InvalidOperationException($"Style mismatch for #{id}.");
    Console.WriteLine($"#{id}: {oldColor} -> {newColor}");
}
Console.WriteLine("Colors match a fresh cascade.");
Console.WriteLine($"Full recompute: {restyle.FullRecompute}");
```

`dotnet run` prints:

```text
#card: rgb(0, 0, 255) -> rgb(255, 0, 0)
#badge: rgb(0, 0, 255) -> rgb(255, 0, 0)
#note: canvastext -> canvastext
Colors match a fresh cascade.
Full recompute: False
```

The note stays `canvastext`, the default text color, because no rule in the example sets a color for `#note`. A failed edit has no new document; `Restyle` rejects a failed edit or an edit from a different snapshot with `ArgumentException`.

## Variations

**Remove the class on the next edit.** Add this after the full program. Apply the next edit to `updated` and pass its result to `restyle.Styles`, not `before`.

```csharp
var removal = updated.Apply([
    Edit.RemoveAttribute(updated.GetElementById("badge"), "class")
]);
if (!removal.Succeeded || removal.Document is not { } restored)
    throw new InvalidOperationException("Could not remove class.");
var next = restyle.Styles.Restyle(removal);
var restoredCard = restored.GetElementById("card");
Console.WriteLine(next.Styles.GetStyle(restoredCard).GetComputedValue("color"));
```

```text
rgb(0, 0, 255)
```

## Related recipes

- [Get computed CSS styles in C#](https://recursiveai.org/onehtml/cookbook/computed-style-csharp/)
- [Edit HTML without reformatting it](https://recursiveai.org/onehtml/cookbook/edit-html-csharp-lossless/)

## The short answer

Keep the `DocumentStyles` for the original document. Apply the edit with `doc.Apply(...)`, then pass the successful result to `styles.Restyle(edit)`. Read computed values from `result.Styles` using nodes from the new document. In the example, the badge gains a class, the card turns red, and the result reports `FullRecompute: False`.

## How does CSS style recalculation work after a DOM edit?

[Style recalculation](https://web.dev/articles/reduce-the-scope-and-complexity-of-style-calculations#style-calculation) decides which selectors match the current tree and which declarations win. It is not layout: knowing the value of `color` or `display` does not tell you the location or size of a rendered box. onehtml does not lay out or paint the HTML.

When you use `Restyle(edit)`, onehtml builds its change description from the edit result. That includes the mapping from old node indices to new ones, which attributes changed, and whether the edit touched a stylesheet source. The mapping matters even if the HTML looks almost the same: the edited document is a different snapshot. `ComputeAll()` in the example fills the original style cache before the edit; you can omit it if all you need is an individual computed value on demand.

The [cascade docs](https://recursiveai.org/onehtml/docs/cascade/#restyle-after-a-change) explain when a full recompute is needed, for example when quirks mode or the cascade’s layer structure changes. If you supply a `StyleChange` yourself rather than using the edit-result overload, a new tree shape without the old-to-new mapping also triggers a full recompute. `FullRecompute` tells you which path ran; it does not change how you read the resulting styles.

## How do you style a parent based on a child’s class?

[`#card:has(> .late)`](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors/:has) selects the card when it has a **direct child** with the `late` class. The rule sets the card’s text color. The badge turns red too, but for a different reason: it inherits the card’s `color`. The note sits outside the card and keeps its color. This is why restyling only the element named in the edit would miss part of the change.

The exact placement of `:has()` matters. In `#card:has(> .late)` the selector styles the card itself. In `#card:has(> .late) + p` it styles the next paragraph instead. For changes that add or remove nodes, onehtml can narrow which matches to check for the first form; it compares matches across the document for the second. That match check is not the same as rebuilding all computed styles.
