From 2cd81f6e59ace8623185e353c07c5f7c77b81e3b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lukas=20D=C3=BCrrenberger?= Date: Tue, 10 Nov 2026 12:37:33 +0100 Subject: [PATCH] Parse the text of a style element as one style sheet --- Source/HtmlRenderer/Core/Parse/HtmlParser.cs | 9 +++++++++ Source/Test/HtmlRenderer.Test/Css/RealWorldTests.cs | 11 +++++++++++ 2 files changed, 20 insertions(+) diff --git a/Source/HtmlRenderer/Core/Parse/HtmlParser.cs b/Source/HtmlRenderer/Core/Parse/HtmlParser.cs index 534ace396..b4d29040c 100644 --- a/Source/HtmlRenderer/Core/Parse/HtmlParser.cs +++ b/Source/HtmlRenderer/Core/Parse/HtmlParser.cs @@ -109,6 +109,15 @@ private static void AddTextBox(HtmlDataToken token, ref CssBox curBox) if (text.Length == 0) return; } + // HtmlKit splits text into several data tokens, e.g. at each '<' in a style element, + // HTML appends them to the preceding Text node (parsing.html#insert-a-char) + var lastChild = curBox.Boxes.Count > 0 ? curBox.Boxes[curBox.Boxes.Count - 1] : null; + if (lastChild != null && lastChild.HtmlTag == null && lastChild.Text != null) + { + lastChild.Text += text; + return; + } + var box = CssBox.CreateBox(curBox); box.Text = text; } diff --git a/Source/Test/HtmlRenderer.Test/Css/RealWorldTests.cs b/Source/Test/HtmlRenderer.Test/Css/RealWorldTests.cs index eaaa04605..a293d3c68 100644 --- a/Source/Test/HtmlRenderer.Test/Css/RealWorldTests.cs +++ b/Source/Test/HtmlRenderer.Test/Css/RealWorldTests.cs @@ -45,6 +45,17 @@ public void ParseCss_WithStandardString_ExpectReadableProperties() Assert.AreEqual(RColor.FromArgb(255, 0, 0), h2Box.ActualBackgroundColor); } + [TestMethod] + [DataRow("#a { --x: \"<\"; } p { color: red }")] + [DataRow("p::before { content: \"<\" } p { color: red }")] + [DataRow("@media (width < 100000px) { p { color: red } }")] + public void StyleElement_TextWithLessThanSign_IsOneStyleSheet(string css) + { + var (root, _) = LayoutHarness.Layout($"

Text

"); + + Assert.AreEqual(RColor.FromArgb(255, 0, 0), FindByTag(root, "p").ActualColor); + } + private static CssBox FindByTag(CssBox root, string tag) { var box = LayoutHarness.Descendants(root).FirstOrDefault(b => b.HtmlTag != null && b.HtmlTag.Name == tag);