Skip to content

Truly independent web browser

LibWeb: Implement the margin collapsing quirk for body and table cells

sideshowbarker43ca5babe1e2
diff --git a/Libraries/LibWeb/CSS/StyleEngineInput.cpp b/Libraries/LibWeb/CSS/StyleEngineInput.cpp
index 49f68ed88b1..8a45efaf6eb 100644
--- a/Libraries/LibWeb/CSS/StyleEngineInput.cpp
+++ b/Libraries/LibWeb/CSS/StyleEngineInput.cpp
@@ -1518,6 +1518,10 @@ enum ElementConstructionFact : u32 {
IsSvgGeometryElement = 1 << 8,
IsHtmlSelectElement = 1 << 9,
IsHtmlProgressOrMeterElement = 1 << 10,
+ // The element's default block-start or block-end margin is one a quirks-mode body or table cell ignores where it
+ // collapses into the cell's or the body's own start or end.
+ HasQuirkyBlockStartMargin = 1 << 11,
+ HasQuirkyBlockEndMargin = 1 << 12,
// The layout algorithm a MathML element's tag name selects, as a MathMLLayoutKind in these bits.
MathMLLayoutKindShift = 16,
MathMLLayoutKindMask = 0x1f << MathMLLayoutKindShift,
@@ -1746,6 +1750,18 @@ static u32 kind_construction_facts(DOM::Element const& element)
set(element.is_svg_geometry_element(), ElementConstructionFact::IsSvgGeometryElement);
set(is<HTML::HTMLSelectElement>(element), ElementConstructionFact::IsHtmlSelectElement);
set(is<HTML::HTMLProgressElement>(element) || is<HTML::HTMLMeterElement>(element), ElementConstructionFact::IsHtmlProgressOrMeterElement);
+ // https://html.spec.whatwg.org/multipage/rendering.html#concept-rendering-elements-with-margins
+ // The elements with default margins are the following elements: blockquote, dir, dl, h1, h2, h3, h4, h5, h6,
+ // listing, menu, ol, p, plaintext, pre, ul, xmp.
+ // AD-HOC: Only the block-end margins of p, and of the elements laid out as preformatted text, are quirky. See
+ // https://github.com/whatwg/html/issues/10296.
+ if (html_element) {
+ auto const& local_name = element.local_name();
+ set(first_is_one_of(local_name, HTML::TagNames::blockquote, HTML::TagNames::dir, HTML::TagNames::dl, HTML::TagNames::h1, HTML::TagNames::h2, HTML::TagNames::h3, HTML::TagNames::h4, HTML::TagNames::h5, HTML::TagNames::h6, HTML::TagNames::listing, HTML::TagNames::menu, HTML::TagNames::ol, HTML::TagNames::p, HTML::TagNames::plaintext, HTML::TagNames::pre, HTML::TagNames::ul, HTML::TagNames::xmp),
+ ElementConstructionFact::HasQuirkyBlockStartMargin);
+ set(first_is_one_of(local_name, HTML::TagNames::listing, HTML::TagNames::p, HTML::TagNames::plaintext, HTML::TagNames::pre, HTML::TagNames::xmp),
+ ElementConstructionFact::HasQuirkyBlockEndMargin);
+ }
facts |= to_underlying(mathml_layout_kind(element)) << ElementConstructionFact::MathMLLayoutKindShift;
return facts;
}
diff --git a/Libraries/LibWeb/Rust/src/css/computed_value_types.rs b/Libraries/LibWeb/Rust/src/css/computed_value_types.rs
index e6bffc0d89d..03938900487 100644
--- a/Libraries/LibWeb/Rust/src/css/computed_value_types.rs
+++ b/Libraries/LibWeb/Rust/src/css/computed_value_types.rs
@@ -467,6 +467,14 @@ pub struct RetainedWillChangePropertyList {
pub length: usize,
}
+/// The bits of [`MiscLayoutValues::user_agent_margin_sides`], one per physical side.
+pub mod user_agent_margin_side {
+ pub const TOP: u8 = 1 << 0;
+ pub const RIGHT: u8 = 1 << 1;
+ pub const BOTTOM: u8 = 1 << 2;
+ pub const LEFT: u8 = 1 << 3;
+}
+
/// The non-inherited values of how a box lays out and outlines that no more specific group holds:
/// appearance, fragmentation breaks, columns, object fitting, outlines, overflow clip margins and
/// float shapes.
@@ -485,6 +493,9 @@ pub struct MiscLayoutValues {
pub computed_appearance: u8,
/// https://drafts.csswg.org/css-ui/#appearance-disabling-properties
pub native_appearance_disabled: bool,
+ /// The physical sides whose margins the user agent's style sheet sets, as [`user_agent_margin_side`] bits.
+ /// Only a quirks-mode document records them, for its margin collapsing quirks.
+ pub user_agent_margin_sides: u8,
pub outline_style: u8,
pub object_fit: u8,
pub column_height: ComputedSize,
diff --git a/Libraries/LibWeb/Rust/src/css/computed_value_views.rs b/Libraries/LibWeb/Rust/src/css/computed_value_views.rs
index 1b2bc14fd2d..c331ff717f3 100644
--- a/Libraries/LibWeb/Rust/src/css/computed_value_views.rs
+++ b/Libraries/LibWeb/Rust/src/css/computed_value_views.rs
@@ -631,6 +631,7 @@ scalar_accessors! {
misc_layout: {
appearance: u8 => appearance,
native_appearance_disabled: bool => native_appearance_disabled,
+ user_agent_margin_sides: u8 => user_agent_margin_sides,
column_fill: u8 => column_fill,
column_span: u8 => column_span,
column_rule_style: u8 => column_rule_style,
diff --git a/Libraries/LibWeb/Rust/src/css/computed_values.rs b/Libraries/LibWeb/Rust/src/css/computed_values.rs
index 0a362cfb5b0..1ed96f615ae 100644
--- a/Libraries/LibWeb/Rust/src/css/computed_values.rs
+++ b/Libraries/LibWeb/Rust/src/css/computed_values.rs
@@ -305,6 +305,7 @@ impl_computed_payload_clone_and_eq!(MiscLayoutValues {
appearance,
computed_appearance,
native_appearance_disabled,
+ user_agent_margin_sides,
outline_style,
object_fit,
column_height,
@@ -4155,9 +4156,11 @@ pub(crate) struct GroupValueFacts {
effective_zoom: f32,
display_before_box_type_transformation: u32,
effective_color_scheme: i8,
+ /// What the origins of the element's winning declarations decide for its box: whether an author declaration
+ /// disables its native appearance (`NATIVE_APPEARANCE_DISABLED_FACT`), and the physical sides whose margins the
+ /// user agent's style sheet sets in a quirks-mode document (`user_agent_margin_side` bits).
/// https://drafts.csswg.org/css-ui/#appearance-disabling-properties
- /// Whether an author declaration disables the element's native appearance.
- native_appearance_disabled: bool,
+ origin_facts: u8,
/// What of the recorded specified values a group build reads in place of computed values, by
/// [`read_in_place_bits_of`], so that a build of another group mostly need not look through them.
read_in_place_bits: u16,
@@ -4166,6 +4169,11 @@ pub(crate) struct GroupValueFacts {
current_color_groups: u32,
}
+/// The bit of [`GroupValueFacts::origin_facts`] that says an author declaration disables the element's native
+/// appearance. The bits below it are `user_agent_margin_side` bits.
+const NATIVE_APPEARANCE_DISABLED_FACT: u8 = 1 << 7;
+const USER_AGENT_MARGIN_SIDES_FACTS: u8 = 0x0f;
+
/// The bits standing for `groups` among the recorded values a group build reads in place: those of
/// their indices, each group sharing its bit with any other sixteen indices away.
fn read_in_place_bits_of(groups: u32) -> u16 {
@@ -4198,7 +4206,7 @@ impl GroupValueFacts {
effective_zoom: 1.0,
display_before_box_type_transformation: 0,
effective_color_scheme: -1,
- native_appearance_disabled: false,
+ origin_facts: 0,
read_in_place_bits: 0,
current_color_groups: 0,
}
@@ -4273,7 +4281,11 @@ impl GroupValueFacts {
}
pub(crate) fn native_appearance_disabled(&self) -> bool {
- self.native_appearance_disabled
+ self.origin_facts & NATIVE_APPEARANCE_DISABLED_FACT != 0
+ }
+
+ pub(crate) fn user_agent_margin_sides(&self) -> u8 {
+ self.origin_facts & USER_AGENT_MARGIN_SIDES_FACTS
}
/// Whether these and `other` publish the same recorded specified values, zoom, box display
@@ -4289,7 +4301,7 @@ impl GroupValueFacts {
&& self.effective_zoom.to_bits() == other.effective_zoom.to_bits()
&& self.display_before_box_type_transformation == other.display_before_box_type_transformation
&& self.effective_color_scheme == other.effective_color_scheme
- && self.native_appearance_disabled == other.native_appearance_disabled
+ && self.origin_facts == other.origin_facts
&& (same_recorded_values
|| (mine.len() == theirs.len()
&& mine.iter().all(|held| {
@@ -4321,9 +4333,9 @@ impl GroupValueFacts {
if self.effective_zoom.to_bits() != other.effective_zoom.to_bits()
|| self.display_before_box_type_transformation != other.display_before_box_type_transformation
|| self.effective_color_scheme != other.effective_color_scheme
- || self.native_appearance_disabled != other.native_appearance_disabled
+ || self.origin_facts != other.origin_facts
{
- return Some("the zoom, box display, color scheme or native appearance".into());
+ return Some("the zoom, box display, color scheme, native appearance or user-agent margins".into());
}
None
}
@@ -4831,6 +4843,8 @@ pub(crate) struct GroupValuesWriter<'a> {
flags: crate::css::computed_longhand_table::LonghandTableFlags,
/// What the computed values depend on, as `DEPENDS_ON_VIEWPORT_METRICS` and the like.
dependency_flags: u8,
+ /// The physical sides whose margins the user agent's style sheet sets, where the computation records them.
+ user_agent_margin_sides: u8,
}
/// A value written over an element's seeded values, at its place among them.
@@ -4900,6 +4914,7 @@ impl<'a> GroupValuesWriter<'a> {
effective_color_scheme: parent.facts.effective_color_scheme(),
flags,
dependency_flags,
+ user_agent_margin_sides: 0,
}
}
@@ -5204,6 +5219,11 @@ impl<'a> GroupValuesWriter<'a> {
self.dependency_flags |= flags;
}
+ /// Records the physical sides whose margins the user agent's style sheet sets, as `user_agent_margin_side` bits.
+ pub(crate) fn set_user_agent_margin_sides(&mut self, sides: u8) {
+ self.user_agent_margin_sides = sides;
+ }
+
/// Records whether an author declaration disables the element's native appearance.
pub(crate) fn set_native_appearance_disabled(&mut self, disabled: bool) {
use crate::css::computed_longhand_table::NATIVE_APPEARANCE_DISABLED;
@@ -5335,7 +5355,12 @@ impl<'a> GroupValuesWriter<'a> {
display_before_box_type_transformation: self.display_before_box_type_transformation,
effective_color_scheme: i8::try_from(self.effective_color_scheme)
.expect("a color scheme is a small code"),
- native_appearance_disabled,
+ origin_facts: self.user_agent_margin_sides
+ | if native_appearance_disabled {
+ NATIVE_APPEARANCE_DISABLED_FACT
+ } else {
+ 0
+ },
read_in_place_bits,
current_color_groups: 0,
},
@@ -6534,6 +6559,7 @@ impl MiscLayoutValues {
appearance: 0,
computed_appearance: 7,
native_appearance_disabled: false,
+ user_agent_margin_sides: 0,
outline_style: 1,
object_fit: 0,
column_height: ComputedSize::keyword(ComputedSizeKind::Auto),
diff --git a/Libraries/LibWeb/Rust/src/css/style/bridge.rs b/Libraries/LibWeb/Rust/src/css/style/bridge.rs
index cf9cb2dc475..57060e0f553 100644
--- a/Libraries/LibWeb/Rust/src/css/style/bridge.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/bridge.rs
@@ -784,6 +784,10 @@ pub mod element_construction_fact {
pub const IS_SVG_GEOMETRY_ELEMENT: u32 = 1 << 8;
pub const IS_HTML_SELECT_ELEMENT: u32 = 1 << 9;
pub const IS_HTML_PROGRESS_OR_METER_ELEMENT: u32 = 1 << 10;
+ /// The element's default block-start or block-end margin is one a quirks-mode body or table cell ignores where it
+ /// collapses into the cell's or the body's own start or end.
+ pub const HAS_QUIRKY_BLOCK_START_MARGIN: u32 = 1 << 11;
+ pub const HAS_QUIRKY_BLOCK_END_MARGIN: u32 = 1 << 12;
/// The layout algorithm a MathML element's tag name selects, as a `MathLayoutKind` in these bits.
pub const MATHML_LAYOUT_KIND_SHIFT: u32 = 16;
pub const MATHML_LAYOUT_KIND_MASK: u32 = 0x1f << MATHML_LAYOUT_KIND_SHIFT;
diff --git a/Libraries/LibWeb/Rust/src/css/style/computed.rs b/Libraries/LibWeb/Rust/src/css/style/computed.rs
index 9aa235d589a..2b75fdc856f 100644
--- a/Libraries/LibWeb/Rust/src/css/style/computed.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/computed.rs
@@ -200,6 +200,11 @@ impl<'a> ViewLonghands<'a> {
self.0.payloads.inherited_values().effective_zoom()
}
+ /// The physical sides whose margins the user agent's style sheet sets, in a quirks-mode document.
+ pub(crate) fn user_agent_margin_sides(self) -> u8 {
+ self.0.rare().value_facts.user_agent_margin_sides()
+ }
+
/// The dependency flags of the record's table, without whether it is in a `display: none`
/// subtree.
pub(crate) fn dependency_flags(self) -> u8 {
diff --git a/Libraries/LibWeb/Rust/src/css/style/engine_sample.rs b/Libraries/LibWeb/Rust/src/css/style/engine_sample.rs
index c72f9fd897a..3bfb4f9e1e1 100644
--- a/Libraries/LibWeb/Rust/src/css/style/engine_sample.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/engine_sample.rs
@@ -233,6 +233,16 @@ impl RetainedState {
if groups & (1 << group_index::ANCHOR) != 0 {
groups |= 1 << group_index::SURROUND;
}
+ // The misc layout group holds which margins the user agent's style sheet sets, which an animated margin
+ // overrides.
+ if longhands.user_agent_margin_sides() != 0
+ && overlay
+ .entries()
+ .iter()
+ .any(|entry| crate::css::table_group_builder::is_margin_longhand(entry.property))
+ {
+ groups |= 1 << group_index::MISC_LAYOUT;
+ }
// Colors resolve against the element's font as it stood when the overlay was last
// published, or against the animated font where the overlay rebuilds the font group.
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/compute.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/compute.rs
index 0aae24ccd43..d536e0165f6 100644
--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/compute.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/compute.rs
@@ -981,6 +981,22 @@ impl RetainedState {
(length, font, author_disables_native_appearance)
};
writer.set_native_appearance_disabled(author_disables_native_appearance);
+ // https://html.spec.whatwg.org/multipage/rendering.html#margin-collapsing-quirks
+ // Layout ignores some margins the user agent's style sheet sets where they collapse into the start or end of
+ // a quirks-mode body or table cell, so it reads which margins those are. Only a quirks-mode document
+ // records them, so they split no style groups anywhere else.
+ if self.document_style_computation_inputs.in_quirks_mode {
+ let (writing_mode, direction) = crate::css::style_compute::writing_mode_and_direction_of(
+ writer.get(prop::WRITING_MODE),
+ writer.get(prop::DIRECTION),
+ );
+ writer.set_user_agent_margin_sides(user_agent_margin_sides(
+ winners,
+ |winner| cascade.priority_of(winner.source, winner.important),
+ writing_mode,
+ direction,
+ ));
+ }
let required_moved = crate::css::style_compute::REQUIRED_DRIVER_INPUTS
.iter()
.filter(|&&property| writer.moved_from_seed(property, seeded_bits))
@@ -1049,9 +1065,9 @@ impl RetainedState {
if initial.color != current_color {
groups |= current_color_groups & !inherited_groups;
}
- // NB: The misc layout group holds whether an author declaration disables the native appearance, which no
- // longhand's value says.
- if values.facts().native_appearance_disabled() {
+ // NB: The misc layout group holds whether an author declaration disables the native appearance, and which
+ // margins the user agent's style sheet sets, which no longhand's value says.
+ if values.facts().native_appearance_disabled() || values.facts().user_agent_margin_sides() != 0 {
groups |= 1 << group_index::MISC_LAYOUT;
}
// The document element's groups all build against no parent.
@@ -2113,7 +2129,8 @@ impl GroupCache {
let inputs = [
u64::from(scheme),
u64::from(facts.display_before_box_type_transformation())
- | (u64::from(facts.native_appearance_disabled()) << u32::BITS),
+ | (u64::from(facts.native_appearance_disabled()) << u32::BITS)
+ | (u64::from(facts.user_agent_margin_sides()) << (u32::BITS + 1)),
u64::from(facts.effective_zoom().to_bits()),
length.viewport_width.to_bits(),
length.viewport_height.to_bits(),
@@ -3031,6 +3048,37 @@ impl WrittenValueChecks {
}
}
+/// The physical sides of an element's margins whose cascaded values come from the user agent's style sheet, as
+/// `user_agent_margin_side` bits: those whose own winning declaration, or that of their flow-relative counterpart where
+/// that one wins over it, is the user agent's.
+fn user_agent_margin_sides(
+ winners: &[Winner],
+ priority_of: impl Fn(&Winner) -> CascadePriority,
+ writing_mode: u8,
+ direction: u8,
+) -> u8 {
+ use crate::css::cascaded_properties::CascadeOrigin;
+ use crate::css::computed_value_types::user_agent_margin_side as side;
+ use crate::css::property_metadata::property_id as prop;
+ [
+ (prop::MARGIN_TOP, side::TOP),
+ (prop::MARGIN_RIGHT, side::RIGHT),
+ (prop::MARGIN_BOTTOM, side::BOTTOM),
+ (prop::MARGIN_LEFT, side::LEFT),
+ ]
+ .into_iter()
+ .filter(|&(physical, _)| {
+ let flow_relative = crate::css::style_compute::map_physical_to_logical_alias(physical, writing_mode, direction);
+ // The winners come in the order the cascade resolved them, rollbacks included, so the first of the two is
+ // the one the logical pair takes its value from.
+ winners
+ .iter()
+ .find(|winner| winner.property == physical || winner.property == flow_relative)
+ .is_some_and(|winner| priority_of(winner).cascade_origin() == CascadeOrigin::UserAgent)
+ })
+ .fold(0, |sides, (_, bit)| sides | bit)
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/Libraries/LibWeb/Rust/src/css/style/style_invalidation.rs b/Libraries/LibWeb/Rust/src/css/style/style_invalidation.rs
index ea395f6dbc9..34c9083fb3b 100644
--- a/Libraries/LibWeb/Rust/src/css/style/style_invalidation.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/style_invalidation.rs
@@ -1216,6 +1216,12 @@ fn record_move_damage(
result.any_computed_value_changed = true;
result.ensure_level(INVALIDATION_RELAYOUT);
}
+ // Which margins the user agent's style sheet sets decides which margins a quirks-mode body or table cell
+ // ignores, which no longhand's value says.
+ if old_values.user_agent_margin_sides() != new_values.user_agent_margin_sides() {
+ result.any_computed_value_changed = true;
+ result.ensure_level(INVALIDATION_RELAYOUT);
+ }
if !can_skip {
if old_values.misc_interaction().implicit_will_change != new_values.misc_interaction().implicit_will_change {
result.merge(property_invalidation(property_id::WILL_CHANGE, old_values, new_values));
diff --git a/Libraries/LibWeb/Rust/src/css/table_group_builder.rs b/Libraries/LibWeb/Rust/src/css/table_group_builder.rs
index 2ffebba6a6f..7f0b835f2c0 100644
--- a/Libraries/LibWeb/Rust/src/css/table_group_builder.rs
+++ b/Libraries/LibWeb/Rust/src/css/table_group_builder.rs
@@ -213,6 +213,61 @@ impl<'a> LonghandSource<'a> {
Self::Values { values, .. } => values.facts().native_appearance_disabled(),
}
}
+
+ /// The physical sides whose margins the user agent's style sheet sets, in a quirks-mode document, and no animation
+ /// of the element overrides.
+ fn user_agent_margin_sides(&self) -> u8 {
+ match self {
+ Self::Longhands {
+ longhands,
+ animated_overlay,
+ } => {
+ let sides = longhands.user_agent_margin_sides();
+ let Some(overlay) = animated_overlay.filter(|_| sides != 0) else {
+ return sides;
+ };
+ let (writing_mode, direction) = crate::css::style_compute::writing_mode_and_direction_of(
+ Some(self.handle(property_id::WRITING_MODE)),
+ Some(self.handle(property_id::DIRECTION)),
+ );
+ sides & !margin_sides_animated_by(overlay, writing_mode, direction)
+ }
+ Self::Values { values, .. } => values.facts().user_agent_margin_sides(),
+ }
+ }
+}
+
+/// Whether `property` is a margin longhand, physical or flow-relative.
+pub(crate) fn is_margin_longhand(property: u16) -> bool {
+ matches!(
+ property,
+ property_id::MARGIN_TOP
+ | property_id::MARGIN_RIGHT
+ | property_id::MARGIN_BOTTOM
+ | property_id::MARGIN_LEFT
+ | property_id::MARGIN_BLOCK_START
+ | property_id::MARGIN_BLOCK_END
+ | property_id::MARGIN_INLINE_START
+ | property_id::MARGIN_INLINE_END
+ )
+}
+
+/// The physical sides, as `user_agent_margin_side` bits, whose margins `overlay` animates, itself or through their
+/// flow-relative counterpart in the given writing mode and direction.
+fn margin_sides_animated_by(overlay: &AnimatedOverlay, writing_mode: u8, direction: u8) -> u8 {
+ use crate::css::computed_value_types::user_agent_margin_side as side;
+ [
+ (property_id::MARGIN_TOP, side::TOP),
+ (property_id::MARGIN_RIGHT, side::RIGHT),
+ (property_id::MARGIN_BOTTOM, side::BOTTOM),
+ (property_id::MARGIN_LEFT, side::LEFT),
+ ]
+ .into_iter()
+ .filter(|&(physical, _)| {
+ let flow_relative = crate::css::style_compute::map_physical_to_logical_alias(physical, writing_mode, direction);
+ overlay.get(physical).is_some() || overlay.get(flow_relative).is_some()
+ })
+ .fold(0, |sides, (_, bit)| sides | bit)
}
/// The C++ Color::value() bit layout.
@@ -2521,9 +2576,11 @@ fn build_misc_layout_group(
parent: GroupShares<'_>,
) -> *const c_void {
let native_appearance_disabled = values.native_appearance_disabled();
+ let user_agent_margin_sides = values.user_agent_margin_sides();
- // NB: The generic builder only decodes property values, which leaves native_appearance_disabled at its default.
- if !native_appearance_disabled {
+ // NB: The generic builder only decodes property values, which leaves native_appearance_disabled and
+ // user_agent_margin_sides at their defaults.
+ if !native_appearance_disabled && user_agent_margin_sides == 0 {
let generic = build_generic_group(group_index::MISC_LAYOUT, values, input, used_color_scheme, parent);
if !generic.is_null() {
return generic;
@@ -2628,6 +2685,7 @@ fn build_misc_layout_group(
payload.appearance = normalized_appearance;
payload.computed_appearance = computed_appearance;
payload.native_appearance_disabled = native_appearance_disabled;
+ payload.user_agent_margin_sides = user_agent_margin_sides;
payload.column_height = ComputedSize::from_data(values.handle(property_id::COLUMN_HEIGHT));
payload.outline_color = outline_color;
payload.column_rule_color = column_rule_color;
diff --git a/Libraries/LibWeb/Rust/src/layout/block_formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/block_formatting_context.rs
index 76d2acd2f0c..baf5433ed39 100644
--- a/Libraries/LibWeb/Rust/src/layout/block_formatting_context.rs
+++ b/Libraries/LibWeb/Rust/src/layout/block_formatting_context.rs
@@ -503,6 +503,18 @@ struct MarginsOfContents<'scan> {
/// Answers whether one of the contents that clears the floats on the given sides would get clearance, where the
/// given margins are those the scan found down to that one's own.
gets_clearance: &'scan dyn Fn(FloatSides, CollapsedMargins) -> bool,
+ /// Whether the margins the scan finds collapse into the block start of a quirks-mode body or table cell, which
+ /// leaves out the quirky ones among them, as laying them out does.
+ ignores_quirky_margins: bool,
+}
+
+impl MarginsOfContents<'_> {
+ /// Adds a margin of a box, which is a quirky one where `is_quirky` says so.
+ fn add_margin_of_box(&mut self, margin: CssPixels, is_quirky: bool) {
+ if !(is_quirky && self.ignores_quirky_margins) {
+ self.margins = self.margins.with_margin_of_box(margin, is_quirky);
+ }
+ }
}
/// Where the block-start border edge of a box would go if the box cleared no float.
@@ -539,6 +551,9 @@ fn round_css_pixels(value: CssPixels) -> CssPixels {
pub(crate) struct CollapsedMargins {
largest_positive: CssPixels,
most_negative: CssPixels,
+ /// The largest of the quirky margins among them, which a quirks-mode body or table cell leaves out where they
+ /// collapse into its block end (see `NodeFacts::ignores_quirky_margins_at_its_edges`).
+ largest_quirky: CssPixels,
}
impl CollapsedMargins {
@@ -556,14 +571,31 @@ impl CollapsedMargins {
}
}
+ /// These margins with a margin of a box, which is a quirky one where `is_quirky` says so.
+ fn with_margin_of_box(self, margin: CssPixels, is_quirky: bool) -> Self {
+ if !is_quirky || margin < CssPixels::default() {
+ return self.with_margin(margin);
+ }
+ Self {
+ largest_quirky: margin.max(self.largest_quirky),
+ ..self
+ }
+ }
+
fn collapsed_with(self, other: Self) -> Self {
Self {
largest_positive: self.largest_positive.max(other.largest_positive),
most_negative: self.most_negative.min(other.most_negative),
+ largest_quirky: self.largest_quirky.max(other.largest_quirky),
}
}
fn collapsed_margin(self) -> CssPixels {
+ self.largest_positive.max(self.largest_quirky) + self.most_negative
+ }
+
+ /// The collapsed margin of these margins, leaving out the quirky ones.
+ fn collapsed_margin_without_quirky_margins(self) -> CssPixels {
self.largest_positive + self.most_negative
}
}
@@ -593,6 +625,9 @@ pub(crate) struct BlockMarginState {
continues_enclosing_margins: bool,
top_margin_group: Option<TopMarginGroup>,
box_last_in_flow_child_margin_bottom_collapsed: bool,
+ /// Whether the margins since the last reset collapse into the block start of a quirks-mode body or table cell,
+ /// which leaves the quirky ones among them out (see `NodeFacts::ignores_quirky_margins_at_its_edges`).
+ ignores_quirky_margins: bool,
}
/// Collapses the block-start margin of a reused child whose contents left `margins_left_by_contents` with the margins in
@@ -602,10 +637,11 @@ pub(crate) struct BlockMarginState {
fn collapse_block_start_margin_of_reused_child(
margin_state: &mut BlockMarginState,
cells: &used_values::RootInputCells,
+ margin_top_is_quirky: bool,
margins_left_by_contents: &mut BlockMarginState,
introduces_clearance: bool,
) -> CssPixels {
- margin_state.add_margin(cells.margin_top());
+ margin_state.add_margin_of_box(cells.margin_top(), margin_top_is_quirky);
if introduces_clearance {
margin_state.reset();
}
@@ -638,6 +674,16 @@ impl BlockMarginState {
continues_enclosing_margins: false,
top_margin_group: None,
box_last_in_flow_child_margin_bottom_collapsed: false,
+ ignores_quirky_margins: false,
+ }
+ }
+
+ /// This margin state, where the margins since its last reset collapse into the block start of a quirks-mode body or
+ /// table cell if `ignores_quirky_margins` says so.
+ fn ignoring_quirky_margins(self, ignores_quirky_margins: bool) -> Self {
+ Self {
+ ignores_quirky_margins,
+ ..self
}
}
@@ -685,14 +731,35 @@ impl BlockMarginState {
}
}
- pub(crate) fn add_margin(&mut self, margin: CssPixels) {
- self.margins_since_reset = self.margins_since_reset.with_margin(margin);
+ /// Adds a margin of a box, which is a quirky one where `is_quirky` says so. A quirky margin that collapses into the
+ /// block start of a quirks-mode body or table cell is left out.
+ pub(crate) fn add_margin_of_box(&mut self, margin: CssPixels, is_quirky: bool) {
+ if is_quirky && self.ignores_quirky_margins {
+ return;
+ }
+ self.margins_since_reset = self.margins_since_reset.with_margin_of_box(margin, is_quirky);
+ }
+
+ /// Whether a quirky margin added now would be left out, as it collapses into the block start of a quirks-mode body
+ /// or table cell.
+ pub(crate) fn ignores_quirky_margins(&self) -> bool {
+ self.ignores_quirky_margins
}
pub(crate) fn current_collapsed_margin(&self) -> CssPixels {
self.margins_since_reset.collapsed_margin()
}
+ /// The collapsed margin that stays inside a block container at its block end, which leaves out the quirky margins
+ /// there in a quirks-mode body or table cell (see `NodeFacts::ignores_quirky_margins_at_its_edges`).
+ fn collapsed_margin_at_block_end_of(&self, facts: &NodeFacts<'_>) -> CssPixels {
+ if facts.ignores_quirky_margins_at_its_edges() {
+ self.margins_since_reset.collapsed_margin_without_quirky_margins()
+ } else {
+ self.current_collapsed_margin()
+ }
+ }
+
pub(crate) fn has_open_top_margin_group(&self) -> bool {
self.top_margin_group.is_some_and(|group| group.open)
}
@@ -718,6 +785,7 @@ impl BlockMarginState {
}
self.margins_since_reset = CollapsedMargins::default();
self.continues_enclosing_margins = false;
+ self.ignores_quirky_margins = false;
}
/// Takes in what the contents of a child left in their margin state, `contents`, once they are laid out.
@@ -738,6 +806,9 @@ impl BlockMarginState {
if !contents.continues_enclosing_margins {
self.continues_enclosing_margins = false;
}
+ // Contents that ended the margins collapsing into the block start of a quirks-mode body or table cell end
+ // them here too.
+ self.ignores_quirky_margins &= contents.ignores_quirky_margins;
}
/// Collapses the margins after a block-level box of the flow: what the contents of the box left in their margin
@@ -751,6 +822,7 @@ impl BlockMarginState {
collapses_through: bool,
continues_in_next_fragment: bool,
margin_bottom: CssPixels,
+ margin_bottom_is_quirky: bool,
) -> CssPixels {
if let Some(contents) = margins_left_by_contents {
self.take_in_margins_left_by_contents(contents);
@@ -761,7 +833,7 @@ impl BlockMarginState {
self.reset();
}
let margin_before_block_end_margin = self.current_collapsed_margin();
- self.add_margin(margin_bottom);
+ self.add_margin_of_box(margin_bottom, margin_bottom_is_quirky);
self.update_open_top_margin_group();
if collapses_through {
self.current_collapsed_margin() - margin_before_block_end_margin
@@ -1407,7 +1479,9 @@ impl<'pass> BlockFormattingContext<'pass> {
previous_line_data: previous_line_data
.filter(|_| !aligns_content_in_block_axis(&NodeFacts::new(&run.pass, run.box_))),
block_offset_of_current_block_container: Cell::new(None),
- margin_states: RefCell::new(vec![BlockMarginState::of_flow_root(run.box_)]),
+ margin_states: RefCell::new(vec![BlockMarginState::of_flow_root(run.box_).ignoring_quirky_margins(
+ NodeFacts::new(&run.pass, run.box_).ignores_quirky_margins_at_its_edges(),
+ )]),
outside_marker_line: Cell::new(None),
outside_marker_line_box_block_size_of_root: Cell::new(None),
floats: RefCell::new(Vec::new()),
@@ -1603,12 +1677,14 @@ impl<'pass> BlockFormattingContext<'pass> {
collapses_through: bool,
continues_in_next_fragment: bool,
margin_bottom: CssPixels,
+ margin_bottom_is_quirky: bool,
) {
self.margin_state_mut().collapse_margins_after_block_level_box(
margins_left_by_contents,
collapses_through,
continues_in_next_fragment,
margin_bottom,
+ margin_bottom_is_quirky,
);
}
@@ -1616,6 +1692,7 @@ impl<'pass> BlockFormattingContext<'pass> {
/// margins after it. Margins that collapse through the box leave the flow where it is. And where they would but
/// for its clearance, the flow goes on from where the margins of the box began, `margins_after_clearance` before
/// its block end.
+ #[allow(clippy::too_many_arguments)]
fn move_flow_past_block_level_box(
&self,
border_box_block_end: CssPixels,
@@ -1624,6 +1701,7 @@ impl<'pass> BlockFormattingContext<'pass> {
margins_after_clearance: Option<CollapsedMargins>,
continues_in_next_fragment: bool,
margin_bottom: CssPixels,
+ margin_bottom_is_quirky: bool,
) {
if let Some(margins_after_clearance) = margins_after_clearance {
self.block_offset_of_current_block_container
@@ -1644,6 +1722,7 @@ impl<'pass> BlockFormattingContext<'pass> {
collapses_through,
continues_in_next_fragment,
margin_bottom,
+ margin_bottom_is_quirky,
);
}
@@ -1657,6 +1736,7 @@ impl<'pass> BlockFormattingContext<'pass> {
margins_after_clearance: Option<CollapsedMargins>,
continues_in_next_fragment: bool,
margin_bottom: CssPixels,
+ margin_bottom_is_quirky: bool,
) -> CssPixels {
let states = self.margin_states.borrow();
let (enclosing, margins_left_by_contents) = if contents_are_in_this_flow {
@@ -1679,6 +1759,7 @@ impl<'pass> BlockFormattingContext<'pass> {
collapses_through,
continues_in_next_fragment,
margin_bottom,
+ margin_bottom_is_quirky,
),
}
}
@@ -3221,10 +3302,15 @@ impl<'pass> BlockFormattingContext<'pass> {
.is_some()
};
let mut contents = MarginsOfContents {
- margins: CollapsedMargins::default().with_margin(block_level_box.block_start_margin),
+ margins: CollapsedMargins::default(),
passed_floats: FloatSides::default(),
gets_clearance: &gets_clearance,
+ ignores_quirky_margins: self.margin_state().ignores_quirky_margins(),
};
+ contents.add_margin_of_box(
+ block_level_box.block_start_margin,
+ self.facts(node).has_quirky_block_start_margin(),
+ );
self.add_margins_of_contents_collapsing_with_block_start_margin(
node,
block_level_box.containing_block_inline_size,
@@ -3436,7 +3522,7 @@ impl<'pass> BlockFormattingContext<'pass> {
let margins_before_child = contents.margins;
let mut child_sides = used_values::RootInputCells::default();
child_sides.resolve_vertical_box_model(&child_style, content_inline_size);
- contents.margins = contents.margins.with_margin(child_sides.margin_top());
+ contents.add_margin_of_box(child_sides.margin_top(), child_facts.has_quirky_block_start_margin());
let margins_collapse_through_child = self.add_margins_of_contents_collapsing_with_block_start_margin(
child,
content_inline_size,
@@ -3454,7 +3540,7 @@ impl<'pass> BlockFormattingContext<'pass> {
if !margins_collapse_through_child {
return false;
}
- contents.margins = contents.margins.with_margin(child_sides.margin_bottom());
+ contents.add_margin_of_box(child_sides.margin_bottom(), child_facts.has_quirky_block_end_margin());
}
}
margins_can_collapse_through_box_itself(facts, false, || cells.border_box_block_size(false))
@@ -4203,11 +4289,15 @@ impl<'pass> BlockFormattingContext<'pass> {
let is_in_flow_candidate = self.run.fragmentainer.is_some() && self.is_first_or_last_in_flow_candidate(node);
let discards_block_start_margin =
is_in_flow_candidate && self.discard_block_start_margin_of_next_child.replace(false);
+ // A quirky block-start margin that collapses into the block start of a quirks-mode body or table cell is left
+ // out, by clearance too.
+ let block_start_margin_is_quirky = self.facts(node).has_quirky_block_start_margin();
+ let ignores_block_start_margin = block_start_margin_is_quirky && self.margin_state().ignores_quirky_margins();
if !discards_block_start_margin {
self.margin_state_mut()
- .add_margin(self.metrics_of(sized_child).margin_top());
+ .add_margin_of_box(self.metrics_of(sized_child).margin_top(), block_start_margin_is_quirky);
}
- let block_start_margin = if discards_block_start_margin {
+ let block_start_margin = if discards_block_start_margin || ignores_block_start_margin {
CssPixels::default()
} else {
self.metrics_of(sized_child).margin_top()
@@ -4626,18 +4716,26 @@ impl<'pass> BlockFormattingContext<'pass> {
self.cells_laid_out_here(sized_child)
.available_inner_space_or_constraints_from(available_space)
};
+ let is_quirky_margin_container = facts.ignores_quirky_margins_at_its_edges();
let margin_state_of_contents = if self.cells_laid_out_here(sized_child).border_top() > CssPixels::default()
|| self.cells_laid_out_here(sized_child).padding_top() > CssPixels::default()
{
// margin-top of block container can't collapse with its children if it has non-zero border or padding.
self.margin_state_mut().reset();
BlockMarginState::of_contents_after_block_start_edge(node)
- } else if box_opens_top_margin_group {
- BlockMarginState::of_contents_collapsing_into_own_block_start_margin(node, introduced_clearance)
- } else if self.margin_state().has_open_top_margin_group() {
- BlockMarginState::of_contents_joining_enclosing_group(node)
+ .ignoring_quirky_margins(is_quirky_margin_container)
} else {
- BlockMarginState::of_contents_continuing_margins_of(node, &self.margin_state())
+ // Contents whose margins collapse with those before them go on leaving out the quirky margins that
+ // collapse into the block start of a quirks-mode body or table cell.
+ let ignores_quirky_margins = is_quirky_margin_container || self.margin_state().ignores_quirky_margins();
+ if box_opens_top_margin_group {
+ BlockMarginState::of_contents_collapsing_into_own_block_start_margin(node, introduced_clearance)
+ } else if self.margin_state().has_open_top_margin_group() {
+ BlockMarginState::of_contents_joining_enclosing_group(node)
+ } else {
+ BlockMarginState::of_contents_continuing_margins_of(node, &self.margin_state())
+ }
+ .ignoring_quirky_margins(ignores_quirky_margins)
};
self.enter_margin_state_of_contents(margin_state_of_contents);
if is_in_flow_candidate {
@@ -4935,6 +5033,7 @@ impl<'pass> BlockFormattingContext<'pass> {
margins_after_clearance,
fragment_facts.breaks.continues_in_next,
metrics.margin_bottom(),
+ self.facts(node).has_quirky_block_end_margin(),
));
let mut deferred_legend = None;
let mut placed = match pending_position {
@@ -4977,6 +5076,7 @@ impl<'pass> BlockFormattingContext<'pass> {
margins_after_clearance,
fragment_facts.breaks.continues_in_next,
metrics.margin_bottom(),
+ self.facts(node).has_quirky_block_end_margin(),
);
let content_offset = pending_position.unwrap_or_default();
@@ -5045,8 +5145,10 @@ impl<'pass> BlockFormattingContext<'pass> {
block_container.cells.content_inline_size,
input.containing_block_constraints,
);
- self.margin_state_mut()
- .add_margin(self.metrics_of(sized_child).margin_top());
+ self.margin_state_mut().add_margin_of_box(
+ self.metrics_of(sized_child).margin_top(),
+ self.facts(node).has_quirky_block_start_margin(),
+ );
self.margin_state_mut().update_open_top_margin_group();
self.resolve_block_size_known_ahead_of_contents(sized_child, &input);
let unplaced = self.lay_out_unplaced_block_level_box(
@@ -5170,12 +5272,15 @@ impl<'pass> BlockFormattingContext<'pass> {
&& !container_facts.is_table_wrapper()
}
+ /// The key of the layout of `node` in the flow, whose contents leave out quirky margins where
+ /// `contents_ignore_quirky_margins` says so.
fn in_flow_block_key_of(
&self,
node: Node,
block_container: Node,
block_container_inline_size: CssPixels,
input: LayoutInput,
+ contents_ignore_quirky_margins: bool,
) -> in_flow_block_cache::InFlowBlockKey {
let stretch_fit_block_margins = sizing_context::stretch_fit_block_margins(
&self.run.pass,
@@ -5189,6 +5294,7 @@ impl<'pass> BlockFormattingContext<'pass> {
self.style(block_container),
stretch_fit_block_margins,
self.outside_marker_line.get(),
+ contents_ignore_quirky_margins,
)
}
@@ -5237,7 +5343,13 @@ impl<'pass> BlockFormattingContext<'pass> {
{
return InFlowReuse::Ineligible;
}
- let key = self.in_flow_block_key_of(node, block_container, block_container_inline_size, input);
+ let key = self.in_flow_block_key_of(
+ node,
+ block_container,
+ block_container_inline_size,
+ input,
+ self.margin_state().ignores_quirky_margins(),
+ );
let validity = fc_run_cache::run_root_validity(&self.run.pass, node);
if fragmentainer.keeps_box_layouts {
return self.in_flow_reuse_storing_layout(key, validity, containing_block_position_in_root);
@@ -5267,7 +5379,13 @@ impl<'pass> BlockFormattingContext<'pass> {
return InFlowReuse::Ineligible;
}
let pass = &self.run.pass;
- let key = self.in_flow_block_key_of(node, block_container, block_container_inline_size, input);
+ let key = self.in_flow_block_key_of(
+ node,
+ block_container,
+ block_container_inline_size,
+ input,
+ self.margin_state().ignores_quirky_margins(),
+ );
let validity = fc_run_cache::run_root_validity(pass, node);
let hit = self
.stored_in_flow_layout_of(node, validity, &key)
@@ -5339,6 +5457,7 @@ impl<'pass> BlockFormattingContext<'pass> {
collapse_block_start_margin_of_reused_child(
&mut margin_state,
&entry.cells,
+ self.facts(node).has_quirky_block_start_margin(),
&mut margins_left_by_contents,
position_past_floats.is_some(),
)
@@ -5371,8 +5490,10 @@ impl<'pass> BlockFormattingContext<'pass> {
containing_block_position_in_root: FfiCssPixelPoint,
) -> bool {
let floats_read = &entry.floats_read_by_contents;
+ // A box that got clearance where it was laid out gets none where no float is left, and clearance resets the
+ // margins its contents collapse with, so its stored layout doesn't stand here either.
if self.floats.borrow().is_empty() {
- return floats_read.floats_in_reach.is_empty();
+ return floats_read.floats_in_reach.is_empty() && !floats_read.introduced_clearance;
}
self.rebuild_float_bands();
let flow_position = self.flow_position();
@@ -5404,6 +5525,7 @@ impl<'pass> BlockFormattingContext<'pass> {
collapse_block_start_margin_of_reused_child(
&mut margin_state,
&entry.cells,
+ self.facts(node).has_quirky_block_start_margin(),
&mut margins_left_by_contents,
position_past_floats.is_some(),
)
@@ -5532,6 +5654,7 @@ impl<'pass> BlockFormattingContext<'pass> {
let block_start_margin = collapse_block_start_margin_of_reused_child(
&mut self.margin_state_mut(),
&metrics,
+ self.facts(node).has_quirky_block_start_margin(),
&mut margins_left_by_contents,
introduces_clearance,
);
@@ -5562,6 +5685,7 @@ impl<'pass> BlockFormattingContext<'pass> {
collapses_through,
false,
metrics.margin_bottom(),
+ self.facts(node).has_quirky_block_end_margin(),
),
}
};
@@ -5600,6 +5724,7 @@ impl<'pass> BlockFormattingContext<'pass> {
margins_after_clearance,
false,
metrics.margin_bottom(),
+ self.facts(node).has_quirky_block_end_margin(),
);
ReusedInFlowChild {
content_offset,
@@ -5883,11 +6008,14 @@ impl<'pass> BlockFormattingContext<'pass> {
&& !facts.is_list_item_marker_box()
&& self.in_flow_child_depends_only_on_its_key_and_floats(child, block_container.node, None)
{
+ // A child laid out ahead of the walk is laid out in a flow of its own, from the block start of the run's
+ // root, where it may leave out quirky margins that its place in the walk keeps.
let key = self.in_flow_block_key_of(
child,
block_container.node,
block_container.cells.content_inline_size,
child_input.clone(),
+ NodeFacts::new(pass, self.run.box_).ignores_quirky_margins_at_its_edges(),
);
let validity = fc_run_cache::run_root_validity(pass, child);
if self.stored_in_flow_layout_of(child, validity, &key).is_some() {
@@ -5965,15 +6093,30 @@ impl<'pass> BlockFormattingContext<'pass> {
if self.outside_marker_line.get() != entry.key.incoming_outside_marker_line {
return false;
}
+ // A child laid out ahead leaves out the quirky margins that collapse into the block start of its run's root,
+ // which holds only where this flow leaves them out at the child's position too.
+ let contents_ignore_quirky_margins = entry.key.contents_ignore_quirky_margins;
+ if contents_ignore_quirky_margins != self.margin_state().ignores_quirky_margins() {
+ return false;
+ }
if !self.has_floating_boxes() {
return true;
}
if self.margin_state().has_open_top_margin_group() {
return false;
}
+ // And clearance ends the margins that collapse into that block start, so the contents keep their quirky
+ // margins where the child gets clearance.
let floats_read = &entry.floats_read_by_contents;
let Some(read_start_from_border_box) = floats_read.read_start_from_border_box else {
- return true;
+ return !contents_ignore_quirky_margins
+ || self
+ .position_past_floats_cleared_by_child_laid_out_ahead(
+ node,
+ entry,
+ containing_block_position_in_root,
+ )
+ .is_none();
};
let group_of_contents_is_negative = entry
.margins_left_by_contents
@@ -5986,26 +6129,19 @@ impl<'pass> BlockFormattingContext<'pass> {
{
return false;
}
- self.rebuild_float_bands();
+ let position_past_floats =
+ self.position_past_floats_cleared_by_child_laid_out_ahead(node, entry, containing_block_position_in_root);
+ if contents_ignore_quirky_margins && position_past_floats.is_some() {
+ return false;
+ }
let flow_position = self.flow_position();
- let position_past_floats = self
- .flow_position_past_floats_cleared_by(
- node,
- flow_position,
- Some(BlockLevelBoxInFlow {
- block_start_margin: entry.cells.margin_top(),
- containing_block_inline_size: entry.key.containing_block_inline_size,
- input: &entry.key.input,
- }),
- containing_block_position_in_root,
- )
- .map(|(position, _)| position);
let block_start_margin = {
let mut margin_state = self.margin_state().clone();
let mut margins_left_by_contents = entry.margins_left_by_contents.clone();
collapse_block_start_margin_of_reused_child(
&mut margin_state,
&entry.cells,
+ self.facts(node).has_quirky_block_start_margin(),
&mut margins_left_by_contents,
position_past_floats.is_some(),
)
@@ -6021,6 +6157,27 @@ impl<'pass> BlockFormattingContext<'pass> {
.is_none_or(|edge| edge <= read_start_in_root)
}
+ /// Where clearance puts a child laid out ahead of this walk among the floats placed so far, if it gets any.
+ fn position_past_floats_cleared_by_child_laid_out_ahead(
+ &self,
+ node: Node,
+ entry: &in_flow_block_cache::InFlowBlockEntry,
+ containing_block_position_in_root: FfiCssPixelPoint,
+ ) -> Option<CssPixels> {
+ self.rebuild_float_bands();
+ self.flow_position_past_floats_cleared_by(
+ node,
+ self.flow_position(),
+ Some(BlockLevelBoxInFlow {
+ block_start_margin: entry.cells.margin_top(),
+ containing_block_inline_size: entry.key.containing_block_inline_size,
+ input: &entry.key.input,
+ }),
+ containing_block_position_in_root,
+ )
+ .map(|(position, _)| position)
+ }
+
/// Places a child laid out ahead of this walk, if that layout holds among the floats placed so far.
fn place_child_if_its_layout_ahead_stands(
&self,
@@ -7472,7 +7629,7 @@ impl<'pass> BlockFormattingContext<'pass> {
// aggregates margins of trailing collapse-through siblings laid out after that child was
// placed. It is run output, not a property of that child: the child keeps its own placed
// margin_bottom, and only the root's automatic block size consumes the aggregate.
- let collapsed_margin = self.margin_state().current_collapsed_margin();
+ let collapsed_margin = self.margin_state().collapsed_margin_at_block_end_of(&root_facts);
// NB: Only the automatic block size of a root with block-level children reads the trailing collapsed margin.
if !root_facts.children_are_inline() {
let index_of_last_child_margins_do_not_collapse_through =
@@ -7555,11 +7712,16 @@ impl<'pass> BlockFormattingContext<'pass> {
outcome.is_placed,
"a block-level box is placed before its line takes it"
);
+ // The margin after the block counts toward the block size of its block container only where the block ends it,
+ // where a quirks-mode body or table cell leaves out the quirky margins.
+ let block_end_margin = self
+ .margin_state()
+ .collapsed_margin_at_block_end_of(&self.facts(containing_block.node));
line_builder.append_block_level_box(
node,
line_index,
block_bottom,
- self.margin_state().current_collapsed_margin(),
+ block_end_margin,
line_box::BlockLevelBoxOnLine {
content_offset: outcome.content_offset,
cells: outcome.cells,
@@ -8213,7 +8375,7 @@ impl<'pass> BlockFormattingContext<'pass> {
if children.is_some_and(|children| children.pending_margins_collapse_through_block_start) {
CssPixels::default()
} else {
- margin_state.current_collapsed_margin()
+ margin_state.collapsed_margin_at_block_end_of(&facts)
};
let metrics = self.metrics_of(sized_child);
if metrics.padding_bottom() == CssPixels::default() && metrics.border_bottom() == CssPixels::default() {
@@ -8234,7 +8396,7 @@ impl<'pass> BlockFormattingContext<'pass> {
let mut margin_bottom = if self.line_clamp_reached() {
last_in_flow_child.margin_bottom
} else {
- margin_state.current_collapsed_margin()
+ margin_state.collapsed_margin_at_block_end_of(&facts)
};
// https://drafts.csswg.org/css2/#collapsing-margins
// If the top and bottom margins of an element with clearance are adjoining, its margins collapse with the
diff --git a/Libraries/LibWeb/Rust/src/layout/in_flow_block_cache.rs b/Libraries/LibWeb/Rust/src/layout/in_flow_block_cache.rs
index 53e3bee12e8..f18c7388584 100644
--- a/Libraries/LibWeb/Rust/src/layout/in_flow_block_cache.rs
+++ b/Libraries/LibWeb/Rust/src/layout/in_flow_block_cache.rs
@@ -36,6 +36,9 @@ pub(super) struct InFlowBlockKey {
pub(super) initial_containing_block_size: (CssPixels, CssPixels),
pub(super) document_in_quirks_mode: bool,
pub(super) document_in_limited_quirks_mode: bool,
+ /// Whether the margins of the contents that collapse with the block-start margin of the box leave out the quirky
+ /// ones, as those collapsing into the block start of a quirks-mode body or table cell do.
+ pub(super) contents_ignore_quirky_margins: bool,
}
impl InFlowBlockKey {
@@ -46,6 +49,7 @@ impl InFlowBlockKey {
container_style: StyleValues<'_>,
stretch_fit_block_margins: (CssPixels, CssPixels),
incoming_outside_marker_line: Option<block_formatting_context::OutsideMarkerLine>,
+ contents_ignore_quirky_margins: bool,
) -> Self {
Self {
input,
@@ -67,6 +71,7 @@ impl InFlowBlockKey {
),
document_in_quirks_mode: run.pass.document_in_quirks_mode,
document_in_limited_quirks_mode: run.pass.document_in_limited_quirks_mode,
+ contents_ignore_quirky_margins,
}
}
}
diff --git a/Libraries/LibWeb/Rust/src/layout/node_facts.rs b/Libraries/LibWeb/Rust/src/layout/node_facts.rs
index 8036f62f82c..05f66d67db0 100644
--- a/Libraries/LibWeb/Rust/src/layout/node_facts.rs
+++ b/Libraries/LibWeb/Rust/src/layout/node_facts.rs
@@ -1648,6 +1648,64 @@ impl<'pass> NodeFacts<'pass> {
pub(crate) fn is_html_body_element(&self) -> bool {
has_flag(self.data(), NodeFlag::IsBody)
}
+
+ // https://html.spec.whatwg.org/multipage/rendering.html#margin-collapsing-quirks
+ // In quirks mode, any element with default margins that is the child of a body, td, or th element and has no
+ // substantial previous siblings is expected to have a user-agent level style sheet rule that sets its
+ // 'margin-block-start' property to zero.
+ // AD-HOC: Instead of that rule and the three after it, which zero the margins of the children of body, td and th by
+ // their siblings, a quirks-mode body or table cell ignores the quirky margins that collapse into its own
+ // start or end, however deep in it they are, and keeps a margin an author sets. See
+ // https://github.com/whatwg/html/issues/10296.
+ /// Whether the box is a quirks-mode body or table cell, which ignores the quirky margins of its contents that
+ /// collapse into its own block-start or block-end.
+ pub(crate) fn ignores_quirky_margins_at_its_edges(&self) -> bool {
+ self.document_in_quirks_mode() && (self.is_html_body_element() || self.display().is_table_cell())
+ }
+
+ /// Whether the block-start margin of the box is a quirky one: one the user agent's style sheet gives an element
+ /// with default margins.
+ pub(crate) fn has_quirky_block_start_margin(&self) -> bool {
+ use crate::css::style::bridge::element_construction_fact;
+ self.has_quirky_margin(element_construction_fact::HAS_QUIRKY_BLOCK_START_MARGIN, true)
+ }
+
+ /// Whether the block-end margin of the box is a quirky one: one the user agent's style sheet gives a p element or
+ /// an element laid out as preformatted text.
+ pub(crate) fn has_quirky_block_end_margin(&self) -> bool {
+ use crate::css::style::bridge::element_construction_fact;
+ self.has_quirky_margin(element_construction_fact::HAS_QUIRKY_BLOCK_END_MARGIN, false)
+ }
+
+ fn has_quirky_margin(&self, construction_fact: u32, is_block_start: bool) -> bool {
+ use crate::css::computed_value_types::user_agent_margin_side;
+ use crate::css::css_enums::writing_mode;
+ if !self.document_in_quirks_mode() {
+ return false;
+ }
+ let Some(style) = self.computed_values_view_if_styled() else {
+ return false;
+ };
+ // The user agent's margins are recorded by physical side, so the block-start and block-end sides are those the
+ // box's writing mode puts there.
+ let (block_start, block_end) = match style.writing_mode() {
+ writing_mode::VERTICAL_RL | writing_mode::SIDEWAYS_RL => {
+ (user_agent_margin_side::RIGHT, user_agent_margin_side::LEFT)
+ }
+ writing_mode::VERTICAL_LR | writing_mode::SIDEWAYS_LR => {
+ (user_agent_margin_side::LEFT, user_agent_margin_side::RIGHT)
+ }
+ _ => (user_agent_margin_side::TOP, user_agent_margin_side::BOTTOM),
+ };
+ let side = if is_block_start { block_start } else { block_end };
+ if style.user_agent_margin_sides() & side == 0 {
+ return false;
+ }
+ let arena = self.pass.arena();
+ arena.dom_node_style_node(self.node).is_some_and(|element| {
+ arena.with_style_store(|engine| engine.element_construction_facts(element)) & construction_fact != 0
+ })
+ }
}
#[cfg(test)]
diff --git a/Tests/LibWeb/Layout/expected/quirks/input-in-pre-quirks-mode.txt b/Tests/LibWeb/Layout/expected/quirks/input-in-pre-quirks-mode.txt
index 957cc2aa88e..d70049feff2 100644
--- a/Tests/LibWeb/Layout/expected/quirks/input-in-pre-quirks-mode.txt
+++ b/Tests/LibWeb/Layout/expected/quirks/input-in-pre-quirks-mode.txt
@@ -1,13 +1,13 @@
-Viewport <#document> at [0,0] [0+0+0 800 0+0+0] [0+0+0 600 0+0+0] [BFC] children: not-inline overflow: [0,0 800x610]
- BlockContainer <html> at [0,0] [0+0+0 800 0+0+0] [0+0+0 610 0+0+0] [BFC] children: not-inline
- BlockContainer <body> at [8,13] [8+0+0 784 0+0+8] [8+0+0 584 0+0+8] children: not-inline
- BlockContainer <pre> at [8,13] [0+0+0 784 0+0+0] [13+0+0 20 0+0+13] children: inline
- frag 0 from TextInputBox start: 0, length: 0, rect: [13,16 167.6875x14] baseline: 14
- TextInputBox <input> at [13,16] inline-block [0+2+3 167.6875 3+2+0] [0+2+1 14 1+2+0] [BFC] children: not-inline
- Box <div> at [13,16] flex-container(row) [0+0+0 167.6875 0+0+0] [0+0+0 14 0+0+0] [FFC] children: not-inline
- BlockContainer <div> at [13,16] flex-item [0+0+0 167.6875 0+0+0] [0+0+0 14 0+0+0] [BFC] children: inline
- frag 0 from TextNode start: 0, length: 0, rect: [13,16 0x14] baseline: 11
+Viewport <#document> at [0,0] [0+0+0 800 0+0+0] [0+0+0 600 0+0+0] [BFC] children: not-inline overflow: [0,0 800x605]
+ BlockContainer <html> at [0,0] [0+0+0 800 0+0+0] [0+0+0 605 0+0+0] [BFC] children: not-inline
+ BlockContainer <body> at [8,8] [8+0+0 784 0+0+8] [8+0+0 584 0+0+8] children: not-inline
+ BlockContainer <pre> at [8,8] [0+0+0 784 0+0+0] [13+0+0 20 0+0+13] children: inline
+ frag 0 from TextInputBox start: 0, length: 0, rect: [13,11 167.6875x14] baseline: 14
+ TextInputBox <input> at [13,11] inline-block [0+2+3 167.6875 3+2+0] [0+2+1 14 1+2+0] [BFC] children: not-inline
+ Box <div> at [13,11] flex-container(row) [0+0+0 167.6875 0+0+0] [0+0+0 14 0+0+0] [FFC] children: not-inline
+ BlockContainer <div> at [13,11] flex-item [0+0+0 167.6875 0+0+0] [0+0+0 14 0+0+0] [BFC] children: inline
+ frag 0 from TextNode start: 0, length: 0, rect: [13,11 0x14] baseline: 11
TextNode <#text> (not painted)
SC for Viewport<#document> [0,0 800x600] (z-index: auto)
- SC for BlockContainer<HTML> [0,0 800x610] (z-index: auto)
+ SC for BlockContainer<HTML> [0,0 800x605] (z-index: auto)
diff --git a/Tests/LibWeb/Text/expected/quirks-mode-margin-collapsing-animated-margins.txt b/Tests/LibWeb/Text/expected/quirks-mode-margin-collapsing-animated-margins.txt
new file mode 100644
index 00000000000..b2ed5706361
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/quirks-mode-margin-collapsing-animated-margins.txt
@@ -0,0 +1,7 @@
+animated-top: 10x60
+animated-top-nested: 10x60
+animated-block-start: 10x60
+animated-other-side: 50x20
+animated-block-start-vertical-rl: 50x10
+canceled before: 10x60
+canceled after: 10x20
diff --git a/Tests/LibWeb/Text/expected/quirks-mode-margin-collapsing-nesting-and-changes.txt b/Tests/LibWeb/Text/expected/quirks-mode-margin-collapsing-nesting-and-changes.txt
new file mode 100644
index 00000000000..fc84df3db41
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/quirks-mode-margin-collapsing-nesting-and-changes.txt
@@ -0,0 +1,34 @@
+body-nested: top 8
+deep: height 20
+blockquote-p: height 36
+padded-cell: height 30
+th: height 20
+css-cell: height 20
+revert: height 20
+revert-physical-over-logical: height 20
+revert-logical-over-physical: height 20
+div-border: height 37
+h1-then-p: height 56
+br-then-p: height 56
+block-in-inline: height 20
+text-then-block-in-inline: height 56
+block-in-inline-then-text: height 56
+vertical-rl-cell: width 20
+vertical-lr-cell: width 20
+vertical-rl-two-paragraphs: width 56
+clear-short-float: height 36, p at 16
+clear-tall-float: height 50, p at 30
+clear-nested: height 40, p at 20
+dyn-style before: 20
+dyn-style author top: 36
+dyn-style removed: 20
+dyn-text inserted: 56
+dyn-text removed: 20
+dyn-class added: 36
+dyn-class removed: 20
+dyn-remove-text: 20
+dyn-float-gone before: 50
+dyn-float-gone no longer floated: 20
+dyn-first-height before: 20
+dyn-first-height 10px: 46
+dyn-first-height 0: 20
diff --git a/Tests/LibWeb/Text/expected/quirks-mode-margin-collapsing-parallel-layout.txt b/Tests/LibWeb/Text/expected/quirks-mode-margin-collapsing-parallel-layout.txt
new file mode 100644
index 00000000000..582575c2bcd
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/quirks-mode-margin-collapsing-parallel-layout.txt
@@ -0,0 +1,7 @@
+second-block: height 56
+second-block-nested: height 56
+many-blocks: height 164
+empty-first-block: height 20
+first-block: height 56
+cleared-block: height 86
+cleared-block-past-short-float: height 66
diff --git a/Tests/LibWeb/Text/expected/quirks-mode-margin-collapsing.txt b/Tests/LibWeb/Text/expected/quirks-mode-margin-collapsing.txt
new file mode 100644
index 00000000000..f1771be2bf1
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/quirks-mode-margin-collapsing.txt
@@ -0,0 +1,22 @@
+compatMode: BackCompat
+body-first: top 8
+one-p: cell height 20
+empty-p-then-text: cell height 20
+two-p: cell height 56
+p-in-div: cell height 20
+author-margin-same: cell height 52
+author-margin-top-only: cell height 36
+text-then-p: cell height 56
+h1-last: cell height 31
+ul: cell height 36
+form: cell height 36
+div-margin-then-p: cell height 30
+script-then-p: cell height 20
+span-then-p: cell height 20
+flex-cell: cell height 52
+p-float: cell height 52
+two-empty-p: cell height 20
+p-then-comment: cell height 20
+p-bfc: cell height 20
+p-inline-block: cell height 52
+pre: cell height 20
diff --git a/Tests/LibWeb/Text/input/quirks-mode-margin-collapsing-animated-margins.html b/Tests/LibWeb/Text/input/quirks-mode-margin-collapsing-animated-margins.html
new file mode 100644
index 00000000000..b01c735fe8b
--- /dev/null
+++ b/Tests/LibWeb/Text/input/quirks-mode-margin-collapsing-animated-margins.html
@@ -0,0 +1,33 @@
+<!DOCTYPE quirks>
+<html><head><meta charset="utf-8"><style>
+body, td { font: 16px/20px sans-serif; } td { padding: 0; vertical-align: top; } table { margin: 0 0 4px; }
+td p { width: 10px; }
+@keyframes top { from, to { margin-top: 40px; } }
+@keyframes block-start { from, to { margin-block-start: 40px; } }
+@keyframes left { from, to { margin-left: 40px; } }
+.top { animation: top 1000s linear; }
+.block-start { animation: block-start 1000s linear; }
+.left { animation: left 1000s linear; }
+</style></head>
+<body>
+<table cellspacing="0"><tr><td id="animated-top"><p class="top">A</p></td></tr></table>
+<table cellspacing="0"><tr><td id="animated-top-nested"><div><p class="top">A</p></div></td></tr></table>
+<table cellspacing="0"><tr><td id="animated-block-start"><p class="block-start">A</p></td></tr></table>
+<table cellspacing="0"><tr><td id="animated-other-side"><p class="left">A</p></td></tr></table>
+<table cellspacing="0"><tr><td id="animated-block-start-vertical-rl" style="writing-mode: vertical-rl"><p class="block-start" style="height: 10px">A</p></td></tr></table>
+<table cellspacing="0"><tr><td id="canceled"><p class="top" id="canceled-p">A</p></td></tr></table>
+<script src="include.js"></script>
+<script>
+ test(() => {
+ const size = id => {
+ const r = document.getElementById(id).getBoundingClientRect();
+ return `${Math.round(r.width)}x${Math.round(r.height)}`;
+ };
+ for (const id of ["animated-top", "animated-top-nested", "animated-block-start", "animated-other-side", "animated-block-start-vertical-rl"])
+ println(`${id}: ${size(id)}`);
+ println(`canceled before: ${size("canceled")}`);
+ for (const animation of document.getElementById("canceled-p").getAnimations()) animation.cancel();
+ println(`canceled after: ${size("canceled")}`);
+ });
+</script>
+</body></html>
diff --git a/Tests/LibWeb/Text/input/quirks-mode-margin-collapsing-nesting-and-changes.html b/Tests/LibWeb/Text/input/quirks-mode-margin-collapsing-nesting-and-changes.html
new file mode 100644
index 00000000000..7db059b9610
--- /dev/null
+++ b/Tests/LibWeb/Text/input/quirks-mode-margin-collapsing-nesting-and-changes.html
@@ -0,0 +1,56 @@
+<!DOCTYPE quirks>
+<html><head><meta charset="utf-8"><style>body, td, th, .cell { font: 16px/20px sans-serif; } td, th { padding: 0; } table { margin: 0 0 4px; } .m { margin-top: 16px; } .cell { display: table-cell; } .float { float: left; width: 30px; }</style></head>
+<body><div id="body-nested"><div><p>Nested in body</p></div></div>
+<table cellspacing="0"><tr><td id="deep"><div><div><p>Deep</p></div></div></td></tr></table>
+<table cellspacing="0"><tr><td id="blockquote-p"><blockquote><p>Quote</p></blockquote></td></tr></table>
+<table cellspacing="0"><tr><td id="padded-cell" style="padding: 5px 0"><p>Padded</p></td></tr></table>
+<table cellspacing="0"><tr><th id="th"><p>Header</p></th></tr></table>
+<div class="cell" id="css-cell"><p>CSS cell</p></div>
+<table cellspacing="0"><tr><td id="revert"><p style="margin: revert">Revert</p></td></tr></table>
+<table cellspacing="0"><tr><td id="revert-physical-over-logical"><p style="margin-block-start: 40px; margin-top: revert">Revert</p></td></tr></table>
+<table cellspacing="0"><tr><td id="revert-logical-over-physical"><p style="margin-top: 40px; margin-block-start: revert">Revert</p></td></tr></table>
+<table cellspacing="0"><tr><td id="div-border"><div style="border-top: 1px solid"><p>Bordered div</p></div></td></tr></table>
+<table cellspacing="0"><tr><td id="h1-then-p"><h1 style="font: inherit">H</h1><p>P</p></td></tr></table>
+<table cellspacing="0"><tr><td id="br-then-p"><br><p>P</p></td></tr></table>
+<table cellspacing="0"><tr><td id="clear-short-float"><div class="float" style="height: 16px"></div><div style="clear: left"><p>Clears</p></div></td></tr></table>
+<table cellspacing="0"><tr><td id="clear-tall-float"><div class="float" style="height: 30px"></div><div style="clear: left"><p>Clears</p></div></td></tr></table>
+<table cellspacing="0"><tr><td id="clear-nested"><div class="float" style="height: 20px"></div><div style="clear: left"><div><p>Clears</p></div></div></td></tr></table>
+<table cellspacing="0"><tr><td id="block-in-inline"><span><p>Block in inline</p></span></td></tr></table>
+<table cellspacing="0"><tr><td id="text-then-block-in-inline">Text<span><p>Block in inline</p></span></td></tr></table>
+<table cellspacing="0"><tr><td id="block-in-inline-then-text"><span><p>Block in inline</p>Text</span></td></tr></table>
+<table cellspacing="0"><tr><td id="vertical-rl-cell" style="writing-mode: vertical-rl"><p>V</p></td></tr></table>
+<table cellspacing="0"><tr><td id="vertical-lr-cell" style="writing-mode: vertical-lr"><p>V</p></td></tr></table>
+<table cellspacing="0"><tr><td id="vertical-rl-two-paragraphs" style="writing-mode: vertical-rl"><p>V</p><p>W</p></td></tr></table>
+<table cellspacing="0"><tr><td id="dyn-style"><p>Dynamic style</p></td></tr></table>
+<table cellspacing="0"><tr><td id="dyn-text"><p>Dynamic text</p></td></tr></table>
+<table cellspacing="0"><tr><td id="dyn-class"><p>Dynamic class</p></td></tr></table>
+<table cellspacing="0"><tr><td id="dyn-remove-text">Text<p>Removed text</p></td></tr></table>
+<table cellspacing="0"><tr><td id="dyn-float-gone"><div class="float" id="gone-float" style="height: 30px"></div><div style="clear: left"><p>Cleared</p></div></td></tr></table>
+<table cellspacing="0"><tr><td id="dyn-first-height"><div id="first-height" style="height: 0"></div><div><p>Sibling grows</p></div></td></tr></table>
+<script src="include.js"></script>
+<script>
+ test(() => {
+ const h = id => Math.round(document.getElementById(id).getBoundingClientRect().height);
+ const lines = [`body-nested: top ${Math.round(document.querySelector("#body-nested p").getBoundingClientRect().top)}`];
+ for (const id of ["deep", "blockquote-p", "padded-cell", "th", "css-cell", "revert", "revert-physical-over-logical", "revert-logical-over-physical", "div-border", "h1-then-p", "br-then-p", "block-in-inline", "text-then-block-in-inline", "block-in-inline-then-text"]) lines.push(`${id}: height ${h(id)}`);
+ const p = id => document.querySelector(`#${id} p`);
+ for (const id of ["vertical-rl-cell", "vertical-lr-cell", "vertical-rl-two-paragraphs"]) lines.push(`${id}: width ${Math.round(document.getElementById(id).getBoundingClientRect().width)}`);
+ for (const id of ["clear-short-float", "clear-tall-float", "clear-nested"]) lines.push(`${id}: height ${h(id)}, p at ${Math.round(p(id).getBoundingClientRect().top - document.getElementById(id).getBoundingClientRect().top)}`);
+ lines.push(`dyn-style before: ${h("dyn-style")}`);
+ p("dyn-style").style.marginTop = "16px"; lines.push(`dyn-style author top: ${h("dyn-style")}`);
+ p("dyn-style").style.marginTop = ""; lines.push(`dyn-style removed: ${h("dyn-style")}`);
+ document.getElementById("dyn-text").prepend("Text"); lines.push(`dyn-text inserted: ${h("dyn-text")}`);
+ document.getElementById("dyn-text").firstChild.remove(); lines.push(`dyn-text removed: ${h("dyn-text")}`);
+ p("dyn-class").classList.add("m"); lines.push(`dyn-class added: ${h("dyn-class")}`);
+ p("dyn-class").classList.remove("m"); lines.push(`dyn-class removed: ${h("dyn-class")}`);
+ document.getElementById("dyn-remove-text").firstChild.remove(); lines.push(`dyn-remove-text: ${h("dyn-remove-text")}`);
+ lines.push(`dyn-float-gone before: ${h("dyn-float-gone")}`);
+ const goneFloat = document.getElementById("gone-float");
+ goneFloat.style.float = "none"; goneFloat.style.height = "0"; lines.push(`dyn-float-gone no longer floated: ${h("dyn-float-gone")}`);
+ lines.push(`dyn-first-height before: ${h("dyn-first-height")}`);
+ document.getElementById("first-height").style.height = "10px"; lines.push(`dyn-first-height 10px: ${h("dyn-first-height")}`);
+ document.getElementById("first-height").style.height = "0"; lines.push(`dyn-first-height 0: ${h("dyn-first-height")}`);
+ for (const line of lines) println(line);
+ });
+</script>
+</body></html>
diff --git a/Tests/LibWeb/Text/input/quirks-mode-margin-collapsing-parallel-layout.html b/Tests/LibWeb/Text/input/quirks-mode-margin-collapsing-parallel-layout.html
new file mode 100644
index 00000000000..081e626db7d
--- /dev/null
+++ b/Tests/LibWeb/Text/input/quirks-mode-margin-collapsing-parallel-layout.html
@@ -0,0 +1,18 @@
+<!DOCTYPE quirks>
+<html><head><meta charset="utf-8"><style>body, td { font: 16px/20px sans-serif; } td { padding: 0; vertical-align: top; } table { margin: 0 0 4px; } .float { float: left; width: 30px; height: 30px; }</style></head>
+<body><script>internals.forceParallelLayout();</script>
+<table cellspacing="0"><tr><td id="second-block"><div>A</div><div><p>B</p></div></td></tr></table>
+<table cellspacing="0"><tr><td id="second-block-nested"><div>A</div><div><div><p>B</p></div></div></td></tr></table>
+<table cellspacing="0"><tr><td id="many-blocks"><div>A</div><div><p>B</p></div><div><p>C</p></div><div><p>D</p></div><div><p>E</p></div></td></tr></table>
+<table cellspacing="0"><tr><td id="empty-first-block"><div style="height: 0"></div><div><p>B</p></div></td></tr></table>
+<table cellspacing="0"><tr><td id="first-block"><div><p>A</p></div><div><p>B</p></div></td></tr></table>
+<table cellspacing="0"><tr><td id="cleared-block"><div class="float"></div><div style="clear: left"><p>P</p></div><div><p>Q</p></div></td></tr></table>
+<table cellspacing="0"><tr><td id="cleared-block-past-short-float"><div class="float" style="height: 10px"></div><div style="clear: left"><p>P</p></div><div><p>Q</p></div></td></tr></table>
+<script src="include.js"></script>
+<script>
+ test(() => {
+ for (const td of document.querySelectorAll("td"))
+ println(`${td.id}: height ${Math.round(td.getBoundingClientRect().height)}`);
+ });
+</script>
+</body></html>
diff --git a/Tests/LibWeb/Text/input/quirks-mode-margin-collapsing.html b/Tests/LibWeb/Text/input/quirks-mode-margin-collapsing.html
new file mode 100644
index 00000000000..1d81377e638
--- /dev/null
+++ b/Tests/LibWeb/Text/input/quirks-mode-margin-collapsing.html
@@ -0,0 +1,32 @@
+<!DOCTYPE quirks>
+<html><head><meta charset="utf-8"><style>body, td { font: 16px/20px sans-serif; } td { padding: 0; } table { margin: 0 0 4px; }</style></head>
+<body><p id="body-first">First paragraph in the body</p>
+<table cellspacing="0"><tr><td id="one-p"><p>Paragraph</p></td></tr></table>
+<table cellspacing="0"><tr><td id="empty-p-then-text"><p></p>Text</td></tr></table>
+<table cellspacing="0"><tr><td id="two-p"><p>First</p><p>Second</p></td></tr></table>
+<table cellspacing="0"><tr><td id="p-in-div"><div><p>Nested</p></div></td></tr></table>
+<table cellspacing="0"><tr><td id="author-margin-same"><p style="margin: 16px 0">Author 16px</p></td></tr></table>
+<table cellspacing="0"><tr><td id="author-margin-top-only"><p style="margin-top: 16px">Author top</p></td></tr></table>
+<table cellspacing="0"><tr><td id="text-then-p">Text<p>P</p></td></tr></table>
+<table cellspacing="0"><tr><td id="h1-last"><h1 style="font: inherit">H1</h1></td></tr></table>
+<table cellspacing="0"><tr><td id="ul"><ul><li>Item</li></ul></td></tr></table>
+<table cellspacing="0"><tr><td id="form"><form>Form</form></td></tr></table>
+<table cellspacing="0"><tr><td id="div-margin-then-p"><div style="margin-top: 10px"></div><p>P</p></td></tr></table>
+<table cellspacing="0"><tr><td id="script-then-p"><script>/**/</script><p>P</p></td></tr></table>
+<table cellspacing="0"><tr><td id="span-then-p"><span></span><p>P</p></td></tr></table>
+<table cellspacing="0"><tr><td id="flex-cell"><div style="display: flex; flex-direction: column"><p>A</p></div></td></tr></table>
+<table cellspacing="0"><tr><td id="p-float"><p style="float: left">Float</p>&nbsp;</td></tr></table>
+<table cellspacing="0"><tr><td id="two-empty-p"><p></p><p></p>Text</td></tr></table>
+<table cellspacing="0"><tr><td id="p-then-comment"><p>P</p><!-- c --></td></tr></table>
+<table cellspacing="0"><tr><td id="p-bfc"><p style="overflow: hidden">P</p></td></tr></table>
+<table cellspacing="0"><tr><td id="p-inline-block"><p style="display: inline-block">P</p></td></tr></table>
+<table cellspacing="0"><tr><td id="pre"><pre style="font: inherit">Pre</pre></td></tr></table>
+<script src="include.js"></script>
+<script>
+ test(() => {
+ const lines = [`compatMode: ${document.compatMode}`, `body-first: top ${Math.round(document.getElementById("body-first").getBoundingClientRect().top)}`];
+ for (const td of document.querySelectorAll("td")) lines.push(`${td.id}: cell height ${Math.round(td.getBoundingClientRect().height)}`);
+ for (const line of lines) println(line);
+ });
+</script>
+</body></html>