Skip to content

Commit 0b33325

Browse files
committed
Implement position:relative/absolute/fixed layout, per CSS 2.1 §9.4.3/§10.3.7
position:relative previously had no layout effect anywhere in this fork (parsed but never read); position:absolute only had ad-hoc partial support (no real containing-block resolution, plain in-flow placement otherwise); position:fixed resolved only against the page and dropped the box's own margin; and `right`/`bottom` were parsed at the CSS-OM level but never dispatched onto a box at all, so they had zero effect under any positioning scheme. Backports PeachPDF's CommitBlockChildOffset placement logic, adapted to this fork's box places-itself (rather than parent-commits-child) layout shape: - Right/Bottom become real box properties, wired through CssUtils the same way Left/Top already were. - position:relative applies a near/far offset (left wins over right when both are set, sign-flipped when only the far edge is) that is purely visual per §9.4.3: RelativeOffsetX/Y record it separately so the new StaticBottom can back it out again, and every sibling- placement/margin-collapse/shrink-to-fit call site that used to read a box's ActualBottom directly now reads StaticBottom instead, so a relatively-positioned box's offset no longer drags its parent's auto height or following siblings down with it. - position:absolute resolves against DomUtils.GetNearestPositioned- Ancestor's padding edge, on both axes anchoring from whichever of the near/far offset is set (right-anchoring reads the box's own already-resolved Size.Width; bottom-anchoring has to wait until this box's own ApplyHeight has run, since auto height depends on this box's own content, so it's corrected via a post-hoc OffsetTop shift instead of resolved inline like every other case here). Absolute boxes with width:auto also now shrink-to-fit their content instead of filling the containing block, matching CSS 2.1 §10.3.7's common case (the full seven-case width-auto-resolution algorithm is not implemented). - position:fixed's offset is now computed once, in PerformLayoutImp once margin/container are guaranteed ready, instead of eagerly from the Left/Top property setters - which used to race ahead of ActualMarginLeft/Top being resolved and cache a margin-less Location that never got recomputed. Porting PeachPDF's shrink-to-fit width tests also surfaced two real, pre-existing bugs in GetMinMaxSumWords (a border/padding sum that never reset between sibling "lines", and no explicit-width floor for a childless block), both already fixed in PeachPDF - backported here too, and re-approves one baseline PDF whose auto-width table column render 1-2px differently now that the fix applies generally, not just to the new absolute-positioning case that surfaced it. Ports the CSS 2.1 §9.4.3/§10.3.7 Acid2 regression tests from PeachPDF covering all of the above; all 9 pass.
1 parent b97ee61 commit 0b33325

9 files changed

Lines changed: 452 additions & 31 deletions

File tree

‎Source/HtmlRenderer/Core/Dom/CssBox.cs‎

Lines changed: 194 additions & 12 deletions
Large diffs are not rendered by default.

‎Source/HtmlRenderer/Core/Dom/CssBoxHr.cs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,9 @@ protected override void PerformLayoutImp(RGraphics g)
4848

4949
var prevSibling = DomUtils.GetPreviousSibling(this);
5050
double left = ContainingBlock.Location.X + ContainingBlock.ActualPaddingLeft + ActualMarginLeft + ContainingBlock.ActualBorderLeftWidth;
51-
double top = (prevSibling == null && ParentBox != null ? ParentBox.ClientTop : ParentBox == null ? Location.Y : 0) + MarginTopCollapse(prevSibling) + (prevSibling != null ? prevSibling.ActualBottom + prevSibling.ActualBorderBottomWidth : 0);
51+
// StaticBottom (not ActualBottom): a relatively-positioned previous sibling's visual offset must
52+
// not drag this rule down with it (CSS 2.1 9.4.3), matching the same fix in CssBox.PerformLayoutImp.
53+
double top = (prevSibling == null && ParentBox != null ? ParentBox.ClientTop : ParentBox == null ? Location.Y : 0) + MarginTopCollapse(prevSibling) + (prevSibling != null ? prevSibling.StaticBottom + prevSibling.ActualBorderBottomWidth : 0);
5254
Location = new RPoint(left, top);
5355
ActualBottom = top;
5456

‎Source/HtmlRenderer/Core/Dom/CssBoxProperties.cs‎

Lines changed: 37 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -571,26 +571,20 @@ public string Left
571571
get { return _left; }
572572
set
573573
{
574+
// Deliberately no eager position:fixed recompute here (as this once had): it raced ahead
575+
// of ActualMarginLeft/Top and ContainingBlock/HtmlContainer being ready and cached a
576+
// margin-less Location that never got recomputed once they were. position:fixed placement
577+
// is instead resolved once, in PerformLayoutImp, once the box is fully set up.
574578
_left = value;
575-
576-
if (Position == CssConstants.Fixed)
577-
{
578-
_location = GetActualLocation(Left, Top);
579-
}
580579
}
581580
}
582581

583582
public string Top
584583
{
585584
get { return _top; }
586-
set {
585+
set
586+
{
587587
_top = value;
588-
589-
if (Position == CssConstants.Fixed)
590-
{
591-
_location = GetActualLocation(Left, Top);
592-
}
593-
594588
}
595589
}
596590

@@ -726,6 +720,37 @@ public string Position
726720
set { _position = value; }
727721
}
728722

723+
public string Right
724+
{
725+
get { return _right; }
726+
set { _right = value; }
727+
}
728+
729+
public string Bottom
730+
{
731+
get { return _bottom; }
732+
set { _bottom = value; }
733+
}
734+
735+
/// <summary>
736+
/// The visual-only offset a <c>position:relative</c> box's placement branch applied, per CSS 2.1
737+
/// §9.4.3 - kept separately so <see cref="StaticBottom"/> can back it back out for margin-collapse/
738+
/// sibling-placement consumers that must lay out against the box's un-offset (static) position.
739+
/// Ported from PeachPDF's CssBox.RelativeOffsetX/Y.
740+
/// </summary>
741+
public double RelativeOffsetX { get; set; }
742+
743+
/// <inheritdoc cref="RelativeOffsetX"/>
744+
public double RelativeOffsetY { get; set; }
745+
746+
/// <summary>
747+
/// <see cref="CssBoxProperties.ActualBottom"/> with any <c>position:relative</c> visual offset
748+
/// backed out - the coordinate a following sibling or this box's own parent (for auto height) must
749+
/// lay out against, since relative positioning "has no effect on the position of any other box"
750+
/// (CSS 2.1 §9.4.3). Ported from PeachPDF's CssBox.StaticBottom.
751+
/// </summary>
752+
public double StaticBottom => ActualBottom - RelativeOffsetY;
753+
729754
public string LineHeight
730755
{
731756
get { return _lineHeight; }

‎Source/HtmlRenderer/Core/Utils/CssConstants.cs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ internal static class CssConstants
9595
public const string Pre = "pre";
9696
public const string PreWrap = "pre-wrap";
9797
public const string PreLine = "pre-line";
98+
public const string Relative = "relative";
9899
public const string Right = "right";
99100
public const string Rtl = "rtl";
100101
public const string SansSerif = "sans-serif";
@@ -103,6 +104,7 @@ internal static class CssConstants
103104
public const string Small = "small";
104105
public const string Smaller = "smaller";
105106
public const string Solid = "solid";
107+
public const string Static = "static";
106108
public const string Sub = "sub";
107109
public const string Super = "super";
108110
public const string Square = "square";

‎Source/HtmlRenderer/Core/Utils/CssUtils.cs‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ internal static class CssUtils
4949
"padding-bottom", "padding-left", "padding-right", "padding-top",
5050
"page-break-inside", "break-inside", "break-before", "break-after", "page-break-before", "page-break-after",
5151
"widows", "orphans", "page",
52-
"left", "top", "width", "max-width", "height", "min-height", "max-height",
52+
"left", "top", "right", "bottom", "width", "max-width", "height", "min-height", "max-height",
5353
"background-color", "background-image", "background-position", "background-repeat",
5454
"content", "color", "display", "direction", "empty-cells", "float", "clear", "box-sizing", "position",
5555
"line-height", "vertical-align", "text-indent", "text-align", "text-decoration-line",
@@ -171,6 +171,10 @@ public static string GetPropertyValue(CssBox cssBox, string propName)
171171
return cssBox.Left;
172172
case "top":
173173
return cssBox.Top;
174+
case "right":
175+
return cssBox.Right;
176+
case "bottom":
177+
return cssBox.Bottom;
174178
case "width":
175179
return cssBox.Width;
176180
case "max-width":
@@ -376,6 +380,12 @@ public static void SetPropertyValue(CssBox cssBox, string propName, string value
376380
case "top":
377381
cssBox.Top = value;
378382
break;
383+
case "right":
384+
cssBox.Right = value;
385+
break;
386+
case "bottom":
387+
cssBox.Bottom = value;
388+
break;
379389
case "width":
380390
cssBox.Width = value;
381391
break;

‎Source/HtmlRenderer/Core/Utils/DomUtils.cs‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,24 @@ public static bool IsBoxHasWhitespace(CssBox box)
231231
return false;
232232
}
233233

234+
/// <summary>
235+
/// The nearest positioned ancestor (CSS 2.1 §10.1: a box whose <c>position</c> is anything other
236+
/// than <c>static</c>) of <paramref name="box"/>, or the document root if none is found - the
237+
/// containing block a <c>position:absolute</c> box's offsets/percentages resolve against. Ported
238+
/// from PeachPDF's DomUtils.GetNearestPositionedAncestor.
239+
/// </summary>
240+
internal static CssBox GetNearestPositionedAncestor(CssBox box)
241+
{
242+
var current = box.ParentBox;
243+
244+
while (current.ParentBox != null && current.Position == CssConstants.Static)
245+
{
246+
current = current.ParentBox;
247+
}
248+
249+
return current;
250+
}
251+
234252
/// <summary>
235253
/// The candidate rectangle being tested against existing floats, either during float placement
236254
/// (<see cref="CssLayoutEngine"/>'s FloatBoxLeft/FloatBoxRight) or while flowing a line's inline
-19 Bytes
Loading

‎Source/Test/HtmlRenderer.IntegrationTest/BoxModel/HrPlacementTests.cs‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,10 @@ public sealed class HrPlacementTests
2828
[TestMethod]
2929
public void ARelativelyPositionedPredecessor_DoesNotDragTheRuleWithIt()
3030
{
31-
// Note: position:relative has no implementation anywhere in this fork's Core at all (confirmed - no
32-
// "Relative"/CssConstants.Relative handling exists in Core/Dom/CssBox.cs or CssBoxProperties.cs), so
33-
// 'top' on a relatively-positioned box is simply ignored; the box never moves in the first place. This
34-
// test still genuinely passes - it just does so because relative offsetting is a no-op here, not because
35-
// it's correctly excluded from the flow calculation the way CSS2.1 requires.
31+
// CSS 2.1 §9.4.3: relative positioning is purely visual - the offset must not affect where a
32+
// following sibling lays out. CssBoxHr.PerformLayoutImp reads prevSibling.StaticBottom (which backs
33+
// the offset back out), not ActualBottom, so the rule ends up in the same place whether or not its
34+
// predecessor is relatively positioned.
3635
var (staticRoot, _) = LayoutHarness.Layout(LayoutHarness.Wrap(
3736
"<div id='a' style='height:40px'></div><hr id='h' style='margin:0'>"));
3837
var (offsetRoot, _) = LayoutHarness.Layout(LayoutHarness.Wrap(
Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
using HtmlRenderer.IntegrationTest.TestSupport;
2+
3+
namespace HtmlRenderer.IntegrationTest.Positioning;
4+
5+
/// <summary>
6+
/// Ported from PeachPDF.Tests' Acid2FeatureVerificationTests.cs (the position:relative/absolute/fixed offset
7+
/// section) and AbsolutePositioningIntegrationTests.cs's shrink-to-fit cases. CSS 2.1 §9.4.3: for each axis of
8+
/// a relatively/absolutely positioned box, the "near" offset (<c>left</c>/<c>top</c>) wins when set; if it's
9+
/// <c>auto</c> and the "far" offset (<c>right</c>/<c>bottom</c>) isn't, the far offset applies with its sign
10+
/// flipped. §9.4.3 also requires relative positioning to be purely visual - it must not affect the parent's
11+
/// content-driven height or any following sibling's layout. §10.3.7: an absolutely positioned box's offsets
12+
/// are measured from its nearest positioned ancestor's PADDING edge, and (like every other positioning scheme)
13+
/// its own margin still applies on top of that offset; with no explicit width, it shrinks to fit its content.
14+
/// <para>
15+
/// The PeachPDF source file's flexbox/grid blockification cases and detached-&lt;thead&gt;/&lt;tfoot&gt;
16+
/// containing-block cases are not ported: this fork has neither a flex/grid layout engine nor the notion of a
17+
/// detached header/footer proxy box those target.
18+
/// </para>
19+
/// </summary>
20+
[DoNotParallelize]
21+
[TestClass]
22+
public sealed class AbsolutePositioningIntegrationTests
23+
{
24+
private const double Delta = 1.0;
25+
26+
[TestMethod]
27+
public void PositionRelative_BottomOffset_MovesBoxOppositeDirection()
28+
{
29+
// top is auto, bottom is set - a positive "bottom" pulls the box UP, i.e. subtracts from Y.
30+
var html = LayoutHarness.Wrap("<div id='t' style='position:relative; bottom:10px; width:10px; height:10px;'></div>");
31+
var (root, _) = LayoutHarness.Layout(html);
32+
var box = LayoutHarness.FindById(root, "t")!;
33+
34+
// Static-flow position is Y=0 (LayoutHarness.Wrap sets body margin:0); "bottom:10px" must move it to Y=-10.
35+
Assert.AreEqual(-10, box.Location.Y, Delta);
36+
}
37+
38+
[TestMethod]
39+
public void PositionRelative_Offset_DoesNotAffectParentHeightOrFollowingSibling()
40+
{
41+
// The offset box (and its descendants) move, but the parent's content-driven height and every
42+
// following sibling must lay out against the STATIC position.
43+
var html = LayoutHarness.Wrap(
44+
"<div id='parent'>"
45+
+ "<div id='shifted' style='position:relative; bottom:-30px; height:40px;'></div>"
46+
+ "</div>"
47+
+ "<div id='after' style='height:10px;'></div>");
48+
var (root, _) = LayoutHarness.Layout(html);
49+
var parent = LayoutHarness.FindById(root, "parent")!;
50+
var shifted = LayoutHarness.FindById(root, "shifted")!;
51+
var after = LayoutHarness.FindById(root, "after")!;
52+
53+
// The offset itself is applied visually: the child sits 30px below the parent's top...
54+
Assert.AreEqual(30, shifted.Location.Y - parent.Location.Y, Delta);
55+
56+
// ...but the parent is still exactly 40px tall (the child's static extent)...
57+
Assert.AreEqual(40, parent.ActualBottom - parent.Location.Y, Delta);
58+
59+
// ...and the following sibling starts at the parent's un-inflated bottom.
60+
Assert.AreEqual(parent.ActualBottom, after.Location.Y, Delta);
61+
}
62+
63+
[TestMethod]
64+
public void PositionRelative_OffsetOnBoxItself_DoesNotShiftFollowingSibling()
65+
{
66+
// "after" must lay out against "shifted"'s static bottom, not its visually offset bottom 25px lower.
67+
var html = LayoutHarness.Wrap(
68+
"<div id='shifted' style='position:relative; top:25px; height:40px;'></div>"
69+
+ "<div id='after' style='height:10px;'></div>");
70+
var (root, _) = LayoutHarness.Layout(html);
71+
var shifted = LayoutHarness.FindById(root, "shifted")!;
72+
var after = LayoutHarness.FindById(root, "after")!;
73+
74+
Assert.AreEqual(25, shifted.RelativeOffsetY, Delta);
75+
Assert.AreEqual(shifted.ActualBottom - 25, after.Location.Y, Delta);
76+
}
77+
78+
[TestMethod]
79+
public void PositionAbsolute_BottomOffset_PositionsRelativeToContainingBlockBottomEdge()
80+
{
81+
var html = LayoutHarness.Wrap(
82+
"<div id='cb' style='position:relative; width:100px; height:100px;'>"
83+
+ "<div id='t' style='position:absolute; bottom:10px; width:10px; height:10px;'></div></div>");
84+
var (root, _) = LayoutHarness.Layout(html);
85+
var cb = LayoutHarness.FindById(root, "cb")!;
86+
var box = LayoutHarness.FindById(root, "t")!;
87+
88+
// Box's bottom edge must sit 10px above the containing block's own bottom (padding) edge.
89+
Assert.AreEqual(cb.ActualBottom - 10, box.ActualBottom, Delta);
90+
}
91+
92+
[TestMethod]
93+
public void PositionAbsolute_WithMarginAndBorderedContainingBlock_AppliesBothCorrectly()
94+
{
95+
var html = LayoutHarness.Wrap(
96+
"<div id='cb' style='position:relative; border:16px solid black; width:100px; height:100px;'>"
97+
+ "<div id='t' style='position:absolute; top:0; left:0; margin:36px 0 0 60px; width:10px; height:10px;'></div></div>");
98+
var (root, _) = LayoutHarness.Layout(html);
99+
var cb = LayoutHarness.FindById(root, "cb")!;
100+
var box = LayoutHarness.FindById(root, "t")!;
101+
102+
// Expected: containing block's PADDING edge (border-box + 16px border) + the box's own margin.
103+
Assert.AreEqual(cb.Location.X + 16 + 60, box.Location.X, Delta);
104+
Assert.AreEqual(cb.Location.Y + 16 + 36, box.Location.Y, Delta);
105+
}
106+
107+
[TestMethod]
108+
public void PositionFixed_WithMargin_AppliesMarginOnTopOfOffset()
109+
{
110+
var html = LayoutHarness.Wrap(
111+
"<div id='t' style='position:fixed; top:10px; left:20px; margin:5px 0 0 8px; width:10px; height:10px;'></div>");
112+
var (root, _) = LayoutHarness.Layout(html);
113+
var box = LayoutHarness.FindById(root, "t")!;
114+
115+
Assert.AreEqual(20 + 8, box.Location.X, Delta);
116+
Assert.AreEqual(10 + 5, box.Location.Y, Delta);
117+
}
118+
119+
[TestMethod]
120+
public void PositionAbsoluteAutoWidth_ShrinksToWidestChild_NotSumOfSiblingBorders()
121+
{
122+
// Three siblings under an absolutely-positioned, auto-width parent: #text (real content, ~short),
123+
// #border1 (80px combined border, no content), #border2 (60px combined border, no content) - the
124+
// correct shrink-to-fit width is #border1's own ~80px (the widest single line), not #border1 +
125+
// #border2's borders summed together (~140px).
126+
var html = LayoutHarness.Wrap(
127+
"<div id='container' style='position:relative; width:400px;'>"
128+
+ "<div id='target' style='position:absolute;'>"
129+
+ "<div id='text'>Hi</div>"
130+
+ "<div id='border1' style='border-left:40px solid black; border-right:40px solid black;'></div>"
131+
+ "<div id='border2' style='border-left:30px solid black; border-right:30px solid black;'></div>"
132+
+ "</div></div>");
133+
var (root, _) = LayoutHarness.Layout(html);
134+
var target = LayoutHarness.FindById(root, "target")!;
135+
136+
var targetWidth = target.ActualRight - target.Location.X;
137+
138+
// Allow a little headroom above 80 for #text's own (much smaller) content contribution.
139+
Assert.IsTrue(targetWidth is >= 79 and <= 100,
140+
$"expected shrink-to-fit width near 80px (the widest single sibling), was {targetWidth}");
141+
}
142+
143+
[TestMethod]
144+
public void PositionAbsoluteAutoWidth_MultipleExplicitWidthSiblings_TakesWidestNotSum()
145+
{
146+
var html = LayoutHarness.Wrap(
147+
"<div id='container' style='position:relative; width:400px;'>"
148+
+ "<div id='target' style='position:absolute;'>"
149+
+ "<div id='wide1' style='width:100px; height:10px;'></div>"
150+
+ "<div id='wide2' style='width:90px; height:10px;'></div>"
151+
+ "</div></div>");
152+
var (root, _) = LayoutHarness.Layout(html);
153+
var target = LayoutHarness.FindById(root, "target")!;
154+
155+
var targetWidth = target.ActualRight - target.Location.X;
156+
157+
// The widest single sibling (100px) should win - the buggy summed-across-siblings result would be
158+
// at least 100+90=190px.
159+
Assert.IsTrue(targetWidth is >= 99 and <= 105,
160+
$"expected shrink-to-fit width near 100px (the widest single sibling), was {targetWidth}");
161+
}
162+
163+
[TestMethod]
164+
public void PositionAbsoluteAutoWidth_NonReplacedInlineChildsExplicitWidth_HasNoEffect()
165+
{
166+
// Per CSS2.1 10.3.3, `width` has no effect on a non-replaced inline-level box - its explicit width
167+
// must not be folded into an ancestor's shrink-to-fit computation.
168+
var html = LayoutHarness.Wrap(
169+
"<div id='container' style='position:relative; width:400px;'>"
170+
+ "<div id='target' style='position:absolute;'>"
171+
+ "<span id='inlineWide' style='display:inline; width:200px;'></span>"
172+
+ "</div></div>");
173+
var (root, _) = LayoutHarness.Layout(html);
174+
var target = LayoutHarness.FindById(root, "target")!;
175+
176+
var targetWidth = target.ActualRight - target.Location.X;
177+
178+
// The inline child's own "width:200px" must be ignored - target should shrink to ~0 (no real
179+
// content), not inflate to 200px.
180+
Assert.IsTrue(targetWidth is >= 0 and <= 20,
181+
$"expected shrink-to-fit width near 0px (inline width has no effect), was {targetWidth}");
182+
}
183+
}

0 commit comments

Comments
 (0)