From aee1d848bd06afc9a4e761ad10a6d8e208e86e43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lukas=20D=C3=BCrrenberger?= Date: Tue, 10 Nov 2026 12:44:55 +0100 Subject: [PATCH] Resolve rem lengths against the root element's font size --- Source/HtmlRenderer/Core/Dom/CssBox.cs | 5 ++ .../HtmlRenderer/Core/Dom/CssBoxProperties.cs | 49 +++++++++++++++++- Source/HtmlRenderer/Core/Dom/CssLength.cs | 11 +++- Source/HtmlRenderer/Core/Dom/CssUnit.cs | 3 +- .../HtmlRenderer/Core/Parse/CssValueParser.cs | 23 ++++++--- .../Core/Parse/RegexParserUtils.cs | 2 +- .../HtmlRenderer/Core/Utils/CssConstants.cs | 5 ++ .../Test/HtmlRenderer.Test/Css/LengthTests.cs | 50 +++++++++++++++++-- 8 files changed, 130 insertions(+), 18 deletions(-) diff --git a/Source/HtmlRenderer/Core/Dom/CssBox.cs b/Source/HtmlRenderer/Core/Dom/CssBox.cs index 60248becdb..c7d580623c 100644 --- a/Source/HtmlRenderer/Core/Dom/CssBox.cs +++ b/Source/HtmlRenderer/Core/Dom/CssBox.cs @@ -354,6 +354,11 @@ public HtmlTag HtmlTag get { return _htmltag; } } + protected override bool IsRootElement + { + get { return _htmltag != null && _htmltag.Name.Equals("html", StringComparison.OrdinalIgnoreCase); } + } + /// /// Gets if this box represents an image /// diff --git a/Source/HtmlRenderer/Core/Dom/CssBoxProperties.cs b/Source/HtmlRenderer/Core/Dom/CssBoxProperties.cs index 0167d22a48..a8e9f83296 100644 --- a/Source/HtmlRenderer/Core/Dom/CssBoxProperties.cs +++ b/Source/HtmlRenderer/Core/Dom/CssBoxProperties.cs @@ -913,6 +913,10 @@ public string FontSize { computedValue = len.ConvertEmToPoints(GetParent().ActualFont.Size).ToString(); } + else if (len.Unit == CssUnit.Rems) + { + computedValue = string.Format(NumberFormatInfo.InvariantInfo, "{0}pt", len.Number * GetRootFontSize()); + } else { computedValue = len.ToString(); @@ -1762,7 +1766,7 @@ public RFont ActualFont fsize = parentSize + 2; break; default: - fsize = CssValueParser.ParseLength(FontSize, parentSize, parentSize, null, true, true); + fsize = CssValueParser.ParseLength(FontSize, parentSize, parentSize, GetRootFontSize(), null, true, true); break; } @@ -1883,7 +1887,7 @@ public double ActualBorderSpacingVertical /// Gets the size of 1em in CSS pixels, per spec: an element's own computed font-size, not /// the font's line-spacing metric (ascent+descent+leading), which is typically 15-30%+ /// larger and would inflate every em-based margin/padding/line-height. - /// is created from a font-size already converted to points ('s + /// is created from a font-size already converted to points ('s /// fontAdjust factor, 72/96, applied when the declared value is in CSS px), so its own /// is in points too - convert back to CSS px (the unit /// every other length in this engine resolves to) with the inverse, 96/72. @@ -1894,6 +1898,47 @@ public double GetEmHeight() return ActualFont.Size * 96d / 72d; } + /// + /// Gets the size of 1rem in CSS pixels, the root element's font size (css-values-4 §6.1.1). + /// + public double GetRemHeight() + { + return GetRootElement().GetEmHeight(); + } + + /// + /// Whether this box is the document's root element. + /// + protected virtual bool IsRootElement + { + get { return false; } + } + + /// + /// Gets the root element, or the topmost box for a fragment without an html element. + /// + private CssBoxProperties GetRootElement() + { + var root = this; + for (var box = this; box != null; box = box.GetParent()) + { + root = box; + if (box.IsRootElement) + break; + } + return root; + } + + /// + /// Gets the font size in points that rem refers to in this box's font-size. + /// + private double GetRootFontSize() + { + // css-values-4 §6.1.1: rem in the root element's own font-size refers to the initial value + var root = GetRootElement(); + return root == this ? CssConstants.FontSize : root.ActualFont.Size; + } + /// /// Ensures that the specified length is converted to pixels if necessary /// diff --git a/Source/HtmlRenderer/Core/Dom/CssLength.cs b/Source/HtmlRenderer/Core/Dom/CssLength.cs index 6b7eebf207..05b00a7211 100644 --- a/Source/HtmlRenderer/Core/Dom/CssLength.cs +++ b/Source/HtmlRenderer/Core/Dom/CssLength.cs @@ -57,14 +57,18 @@ public CssLength(string length) } //Get units of the length - string u = length.Substring(length.Length - 2, 2); + string u = length.EndsWith(CssConstants.Rem) ? CssConstants.Rem : length.Substring(length.Length - 2, 2); //Number of the length - string number = length.Substring(0, length.Length - 2); + string number = length.Substring(0, length.Length - u.Length); //TODO: Units behave different in paper and in screen! switch (u) { + case CssConstants.Rem: + _unit = CssUnit.Rems; + _isRelative = true; + break; case CssConstants.Em: _unit = CssUnit.Ems; _isRelative = true; @@ -218,6 +222,9 @@ public override string ToString() case CssUnit.Ems: u = "em"; break; + case CssUnit.Rems: + u = "rem"; + break; case CssUnit.Pixels: u = "px"; break; diff --git a/Source/HtmlRenderer/Core/Dom/CssUnit.cs b/Source/HtmlRenderer/Core/Dom/CssUnit.cs index 269893e8d5..86d1b8de89 100644 --- a/Source/HtmlRenderer/Core/Dom/CssUnit.cs +++ b/Source/HtmlRenderer/Core/Dom/CssUnit.cs @@ -28,6 +28,7 @@ internal enum CssUnit Centimeters, Milimeters, Points, - Picas + Picas, + Rems } } \ No newline at end of file diff --git a/Source/HtmlRenderer/Core/Parse/CssValueParser.cs b/Source/HtmlRenderer/Core/Parse/CssValueParser.cs index 46e3d8e6ce..93e08bedb6 100644 --- a/Source/HtmlRenderer/Core/Parse/CssValueParser.cs +++ b/Source/HtmlRenderer/Core/Parse/CssValueParser.cs @@ -111,6 +111,10 @@ public static bool IsValidLength(string value) { number = value.Substring(0, value.Length - 1); } + else if (value.EndsWith(CssConstants.Rem)) + { + number = value.Substring(0, value.Length - 3); + } else if (value.Length > 2) { number = value.Substring(0, value.Length - 2); @@ -216,7 +220,7 @@ private static void AppendFontFaceCandidate(List result, List. + /// recognizer only, used to gate the evaluation branch in . /// public static bool IsCalcFunction(string value) { @@ -284,7 +288,7 @@ public static double ParseNumber(string number, double hundredPercent) /// the parsed length value with adjustments public static double ParseLength(string length, double hundredPercent, CssBoxProperties box, bool fontAdjust = false) { - return ParseLength(length, hundredPercent, box.GetEmHeight(), null, fontAdjust, false); + return ParseLength(length, hundredPercent, box.GetEmHeight(), box.GetRemHeight(), null, fontAdjust, false); } /// @@ -297,7 +301,7 @@ public static double ParseLength(string length, double hundredPercent, CssBoxPro /// the parsed length value with adjustments public static double ParseLength(string length, double hundredPercent, CssBoxProperties box, string defaultUnit) { - return ParseLength(length, hundredPercent, box.GetEmHeight(), defaultUnit, false, false); + return ParseLength(length, hundredPercent, box.GetEmHeight(), box.GetRemHeight(), defaultUnit, false, false); } /// @@ -306,11 +310,12 @@ public static double ParseLength(string length, double hundredPercent, CssBoxPro /// Specified length /// Equivalent to 100 percent when length is percentage /// + /// the root element's font size, in the same unit as /// /// if the length is in pixels and the length is font related it needs to use 72/96 factor /// Allows the return double to be in points. If false, result will be pixels /// the parsed length value with adjustments - public static double ParseLength(string length, double hundredPercent, double emFactor, string defaultUnit, bool fontAdjust, bool returnPoints) + public static double ParseLength(string length, double hundredPercent, double emFactor, double remFactor, string defaultUnit, bool fontAdjust, bool returnPoints) { //Return zero if no length specified, zero specified if (string.IsNullOrEmpty(length) || length == "0") @@ -327,7 +332,7 @@ public static double ParseLength(string length, double hundredPercent, double em if (TryGetCalcFunction(length, out calcFunction)) { var node = CalcParser.Parse(calcFunction); - var context = new CalcContext(hundredPercent, emFactor, emFactor, fontAdjust, returnPoints); + var context = new CalcContext(hundredPercent, emFactor, remFactor, fontAdjust, returnPoints); var pixels = node != null ? CalcEvaluator.Evaluate(node, context) : null; return pixels ?? 0d; } @@ -340,7 +345,7 @@ public static double ParseLength(string length, double hundredPercent, double em double factor; //Number of the length - string number = hasUnit ? length.Substring(0, length.Length - 2) : length; + string number = hasUnit ? length.Substring(0, length.Length - unit.Length) : length; //TODO: Units behave different in paper and in screen! switch (unit) @@ -348,6 +353,9 @@ public static double ParseLength(string length, double hundredPercent, double em case CssConstants.Em: factor = emFactor; break; + case CssConstants.Rem: + factor = remFactor; + break; case CssConstants.Ex: factor = emFactor / 2; break; @@ -388,9 +396,10 @@ public static double ParseLength(string length, double hundredPercent, double em /// private static string GetUnit(string length, string defaultUnit, out bool hasUnit) { - var unit = length.Length >= 3 ? length.Substring(length.Length - 2, 2) : string.Empty; + var unit = length.EndsWith(CssConstants.Rem) ? CssConstants.Rem : length.Length >= 3 ? length.Substring(length.Length - 2, 2) : string.Empty; switch (unit) { + case CssConstants.Rem: case CssConstants.Em: case CssConstants.Ex: case CssConstants.Px: diff --git a/Source/HtmlRenderer/Core/Parse/RegexParserUtils.cs b/Source/HtmlRenderer/Core/Parse/RegexParserUtils.cs index 64e2891d92..a3f90ff50b 100644 --- a/Source/HtmlRenderer/Core/Parse/RegexParserUtils.cs +++ b/Source/HtmlRenderer/Core/Parse/RegexParserUtils.cs @@ -46,7 +46,7 @@ internal static class RegexParserUtils /// /// Extracts CSS lengths; e.g. 9px 3pt .89em /// - public const string CssLength = @"([0-9]+|[0-9]*\.[0-9]+)(em|ex|px|in|cm|mm|pt|pc)"; + public const string CssLength = @"([0-9]+|[0-9]*\.[0-9]+)(rem|em|ex|px|in|cm|mm|pt|pc)"; /// /// Extracts line-height values (normal, numbers, lengths, percentages) diff --git a/Source/HtmlRenderer/Core/Utils/CssConstants.cs b/Source/HtmlRenderer/Core/Utils/CssConstants.cs index fdeade96a2..d4d050ac6d 100644 --- a/Source/HtmlRenderer/Core/Utils/CssConstants.cs +++ b/Source/HtmlRenderer/Core/Utils/CssConstants.cs @@ -163,6 +163,11 @@ internal static class CssConstants /// public const string Em = "em"; + /// + /// Rem - The font size of the root element + /// + public const string Rem = "rem"; + /// /// The 'x-height' of the relevan font /// diff --git a/Source/Test/HtmlRenderer.Test/Css/LengthTests.cs b/Source/Test/HtmlRenderer.Test/Css/LengthTests.cs index d5fed4ae10..abcbea841c 100644 --- a/Source/Test/HtmlRenderer.Test/Css/LengthTests.cs +++ b/Source/Test/HtmlRenderer.Test/Css/LengthTests.cs @@ -1,3 +1,4 @@ +using HtmlRenderer.Test.TestSupport; using TheArtOfDev.HtmlRenderer.Core.Dom; namespace HtmlRenderer.Test.Css; @@ -14,9 +15,9 @@ namespace HtmlRenderer.Test.Css; /// IFormattable, and predefined constants (Zero/Half/Full/Thin/Medium/Thick). /// /// HTML-Renderer's internal is much smaller: it has only a single -/// string-parsing constructor (new CssLength("10px")), a 9-member enum -/// (None, Ems, Pixels, Ex, Inches, Centimeters, Milimeters, Points, Picas - i.e. only em/ex/px/mm/cm/ -/// in/pt/pc, no rem/%/ch/viewport/container-query units at all; percentage is tracked separately via +/// string-parsing constructor (new CssLength("10px")), a 10-member enum +/// (None, Ems, Pixels, Ex, Inches, Centimeters, Milimeters, Points, Picas, Rems - i.e. only em/ex/px/mm/cm/ +/// in/pt/pc/rem, no %/ch/viewport/container-query units at all; percentage is tracked separately via /// IsPercentage/Number rather than being a value), Number, /// HasError, IsPercentage, IsRelative (no IsAbsolute), Length (the /// original string), ConvertEmToPoints(emSize)/ConvertEmToPixels(pixelFactor) (Ems-only, @@ -28,7 +29,7 @@ namespace HtmlRenderer.Test.Css; /// Tests below that exercise only the 8 units/members this fork actually supports are ported as plain /// passing tests against the real constructor/members (a few reusing ConvertEmToPoints/ /// ConvertEmToPixels as the closest real analog to PeachPDF's richer pixel-conversion API). -/// Tests that need an unsupported unit (rem, %-as-a-unit, ch, any viewport or container-query variant) +/// Tests that need an unsupported unit (%-as-a-unit, ch, any viewport or container-query variant) /// or an API member this fork's doesn't have (TryParse, To, ToPixel(s), /// comparison/equality operators, IFormattable, predefined constants, IsAbsolute, UnitString, GetUnit) /// are ported under [Ignore], adapted as closely as possible to compile against the real API @@ -36,7 +37,7 @@ namespace HtmlRenderer.Test.Css; /// The container-query-unit theory (ToPixels_ContainerRelativeUnit_*, 4 methods), the viewport-unit /// theories (ToPixels_ViewportUnit_*, 2 methods), ToPixels_Rem_UsesRemFactor, and /// ToPixels_Ch_ApproximatesHalfEm were dropped entirely: their units (cqw/cqh/cqi/cqb/cqmin/cqmax, vw/ -/// vh/vmin/vmax and the sv*/lv*/dv* variants, rem, ch) have no representation whatsoever in +/// vh/vmin/vmax and the sv*/lv*/dv* variants, ch) have no representation whatsoever in /// , so there is no plausible compileable adaptation - constructing a /// with any of those suffixes just falls into the "unrecognized unit" /// HasError branch and asserts nothing meaningful. @@ -66,6 +67,7 @@ public void Constructor_SetsValueAndType() [DataRow("in", "Inches")] [DataRow("pt", "Points")] [DataRow("pc", "Picas")] + [DataRow("rem", "Rems")] [DataRow("bogus", "None")] public void Constructor_ParsesKnownUnitSuffixes(string suffix, string expectedUnitName) { @@ -414,6 +416,44 @@ public void PredefinedConstants_HaveExpectedValues() Assert.AreEqual(5d, thick.Number); } + [TestMethod] + public void Rem_ResolvesAgainstTheRootFontSize() + { + var x = LayoutRem("html{font-size:10px} #x{font-size:20px;margin-left:2rem;padding-left:calc(1rem);text-indent:3rem;height:4rem;border-left:0.5rem solid}"); + + Assert.AreEqual(20, x.ActualMarginLeft, 0.01); + Assert.AreEqual(10, x.ActualPaddingLeft, 0.01); + Assert.AreEqual(30, x.ActualTextIndent, 0.01); + Assert.AreEqual(40, x.Size.Height, 0.01); + Assert.AreEqual(5, x.ActualBorderLeftWidth, 0.01); + } + + [TestMethod] + public void Rem_InFontSize_ResolvesAgainstTheRootFontSize() + { + var x = LayoutRem("html{font-size:10px} body{font-size:30px} #x{font-size:1.5rem}"); + + Assert.AreEqual(15, x.GetEmHeight(), 0.01); + } + + [TestMethod] + public void Rem_InTheRootFontSize_IsTheInitialFontSize() + { + var x = LayoutRem("html{font-size:2rem} #x{margin-left:1rem}"); + var initial = 11d * 96d / 72d; + + Assert.AreEqual(2 * initial, x.GetEmHeight(), 0.01); + Assert.AreEqual(2 * initial, x.ActualMarginLeft, 0.01); + } + + private static CssBox LayoutRem(string css) + { + var (root, _) = LayoutHarness.Layout($"
a
"); + var x = LayoutHarness.FindById(root, "x"); + Assert.IsNotNull(x); + return x!; + } + private static string ExpectedUnitString(string unitName) => unitName switch { "None" => "",