Commit graph

96 commits

Author SHA1 Message Date
R-Goc
094e4bacf8 LibWeb: Deduplicate gap_to_px
This commit creates one common gap_to_px function. This resolves problem
in the unity build.
2026-04-09 08:33:40 -04:00
Shannon Booth
af03e07f90 LibWeb: Clamp replaced element min/max sizes in the content box space
The replaced element sizing code was comparing tentative used sizes
min-width/min-height and max-width/max-height. For box-sizing:
border-box, that mixes content-box and border-box measurements, which
can clamp replaced-like elements incorrectly.

This could make, for example search/text inputs with explicit height
and padding render too short.

Resolve min/max constraints with calculate_inner_width() and
calculate_inner_height() before clamping so the comparison uses
the same inner sizing space as the tentative replaced size.

Fixes the sizing of the search bar on:

https://tv.apple.com/se
2026-04-06 12:35:12 +02:00
Andreas Kling
9526dfbef3 LibWeb: Use fragment extents for orthogonal inline widths
Inline formatting contexts in vertical writing modes were measuring
intrinsic width from the line box width. That width still tracks the
line-height-sized horizontal span, so shrink-to-fit abspos sizing could
stay at 50px even when the text fragments only covered 25px.

Measure the physical horizontal extent from the line box fragments
instead, including the float-aware block formatting context path. This
makes orthogonal inline content report the correct intrinsic width.
2026-04-05 00:03:22 +02:00
Andreas Kling
d75934edf5 LibWeb: Don't mark auto height as definite for abspos non-BFC elements
When an absolutely positioned non-BFC element (flex, grid, etc.) has
auto height, we pre-compute its height from content before running
inside layout. Previously, this content-derived height was marked as
"definite", which incorrectly allowed descendants to resolve percentage
heights against it. Per CSS 2.1 section 10.5, percentage heights should
only resolve when the containing block's height is specified explicitly.

The fix is to simply not set has_definite_height when the CSS height is
auto. This naturally prevents percentage resolution through all existing
paths (set_node, should_treat_height_as_auto, calculate_inner_height)
without needing any new flags or per-site checks.

Two additional fixes enable this:

- In flex line cross-size clamping, remove the contains_percentage()
  guard that prevented percentage min/max-height from resolving. These
  percentages resolve correctly via calculate_inner_height's containing
  block lookup, since the abspos element's containing block always has
  a definite height.

- In grid item alignment, check should_treat_height/width_as_auto for
  percentage preferred sizes, so they're treated as auto when the grid
  container's height is indefinite (CSS Grid section 6.6).
2026-04-03 14:29:44 +02:00
Jelle Raaijmakers
4293c841f3 LibWeb: Implement CSS anchor positioning
When `position-anchor` is used, resolve the insets for that absolutely
positioned box.

Co-authored-by: Rob Ryan <rob@affclicks.com>
2026-04-01 19:41:46 +01:00
Psychpsyo
ca99e65d83 LibWeb: Establish formatting context due to container-type 2026-03-30 15:43:39 +01:00
Andreas Kling
8836f28267 LibWeb: Don't walk past anonymous table cells for percentage resolution
When resolving percentage heights/widths against the containing block,
we walk past anonymous boxes to find the relevant ancestor. However,
anonymous table cells are proper containing blocks with their own
sizing semantics. Walking past them caused us to reach the viewport
and incorrectly resolve percentages against the viewport size.

Fix this in all affected places in FormattingContext:
- should_treat_height_as_auto()
- calculate_inner_height()
- should_treat_max_height_as_none()
- should_treat_max_width_as_none()
- compute_inset() percentage-as-auto check
- solve_replaced_size_constraint()
- compute_height_for_replaced_element()
2026-03-23 16:40:38 +01:00
Tim Ledbetter
60334b3464 LibWeb: Treat percentage insets as auto for indefinite containing blocks 2026-03-20 15:58:50 -05:00
dominick038
76c65eca57 LibWeb: Clamp saturated CSSPixels values before make_definite() 2026-03-11 17:23:35 +01:00
Psychpsyo
f7e1c8cf6b LibWeb: Add spec comment to algorithm 2026-03-07 17:17:18 +01:00
Aliaksandr Kalenik
edf1ca8f19 LibWeb: Restrict throwaway layout states to their subtree
Throwaway LayoutState instances used for intrinsic sizing should not
access nodes outside the laid-out subtree. Make this explicit by setting
a subtree root on each throwaway state, pre-populating only the
immediate containing block, and using try_get() for any ancestor
lookups — treating unavailable ancestors as indefinite rather than
silently populating them with incorrectly-resolved values.
2026-02-27 19:11:41 +01:00
Zaggy1024
dd0c821291 LibWeb: Allow replaced elements to host children
We add a new formatting context that simply runs layout for an
anonymous block formatting context within it. This allows replaced
elements to contain children, if the parent rewrites inline-flow to
inline-block.
2026-02-23 07:27:31 +01:00
Aliaksandr Kalenik
eb210bb3af LibWeb: Replace OrderedHashMap with page-table Vector in LayoutState
Each NodeWithStyle is assigned a sequential layout index during the
pre-layout tree traversal. LayoutState stores UsedValues in a
PagedStore — a two-level page table indexed by layout_index that
gives O(1) lookup via two array accesses, with pages allocated
lazily on first write. UsedValues are stored directly in pages
(Optional<T>) rather than behind heap pointers, eliminating
per-entry malloc/free calls and improving cache locality.

This cuts ensure_used_values_for() from ~14% to ~7% in profiles
on https://www.nyan.cat/.
2026-02-23 01:13:35 +01:00
Tim Ledbetter
8240fa0dc8 LibWeb: Resolve percentage table widths in wrapper width computation
Previously, a table with `width: 100%` and `margin: auto` whose content
was narrower than the viewport would be centered based on content
width rather than filling the containing block. Resizing the viewport
wider than the content would shift the table progressively further to
the right.

Co-authored-by: Aliaksandr Kalenik <kalenik.aliaksandr@gmail.com>
2026-02-21 05:16:56 +01:00
Aliaksandr Kalenik
e87fece8c6 LibWeb: Force position:static on non-root SVG elements
SVG elements (except the outermost <svg>) use SVG's coordinate system,
not the CSS box model, so CSS positioning doesn't apply to them.

This adds SVGElement::adjust_computed_style() to force position:static
on all SVG elements except the outermost <svg> element (which has no
owner_svg_element()). SVGSymbolElement's existing override now calls
Base::adjust_computed_style() to inherit this behavior.

With this in place, the FIXME in layout_absolutely_positioned_element()
for SVG boxes becomes unreachable and is replaced with
VERIFY_NOT_REACHED().
2026-02-21 05:12:55 +01:00
Aliaksandr Kalenik
65704e57fb LibWeb: Fix abspos replaced element constraint equations
The constraint equations for absolutely positioned replaced elements
only subtracted content width/height from the containing block size,
omitting padding and border.

Fixes https://github.com/LadybirdBrowser/ladybird/issues/7820
2026-02-19 12:56:40 +01:00
Aliaksandr Kalenik
36ca93908a LibWeb: Unify abspos containing block resolution across FCs
Introduce AbsposContainingBlockInfo and a virtual
resolve_abspos_containing_block_info() method on FormattingContext that
computes the containing block rect, per-axis positioning mode (static
position vs inset-from-rect), and optional grid alignment — all in one
place.

The base implementation handles the common case: padding-box rect of
the containing block, with inline containing block support. GFC
overrides it to return the grid area rect with alignment info.

This replaces the per-context abspos loops that BFC, FFC, TFC, and GFC
each had, with a shared layout_absolutely_positioned_children() +
layout_absolutely_positioned_element() pair. The offset computation is
simplified from ~40 lines of branching to a data-driven dispatch on the
axis mode, and GFC's ~130-line custom layout method is replaced by a
~30-line resolve override.
2026-02-14 22:50:24 +01:00
Aliaksandr Kalenik
a3a6d73145 LibWeb: Replace static position ancestor walk with cumulative offset
Replace content_box_rect_in_static_position_ancestor_coordinate_space()
which walked the ancestor chain to compute the offset between an abspos
element's static position containing block and its actual containing
block.

Instead, add a cumulative_offset() method to UsedValues that computes
the absolute offset from the ICB to a box's content edge by walking the
containing block chain. For pre-populated nodes during partial relayout,
it returns a cached value from the paintable's absolute position.

The static-CB-to-actual-CB offset is now a simple subtraction of two
cumulative offsets, which also fixes a bug where table cells with
position:relative ancestors got incorrect static positions due to the
old function accumulating offsets in the wrong coordinate space.

Also route direct UsedValues::offset assignments in Flex, Grid, and
Table formatting contexts through set_content_offset().
2026-02-14 18:44:50 +01:00
Tim Ledbetter
66e9e2de4b LibWeb: Account for table padding in intrinsic table width calculation 2026-02-11 09:39:11 +01:00
Andreas Kling
171dfa4db8 LibWeb: Use re-solve pattern for abspos height min/max constraints
The CSS spec (CSS2 10.6.4 / CSS Position 5.3) says:
1. Compute tentative height without min/max-height
2. If result > max-height, re-solve with max-height as height
3. If result < min-height, re-solve with min-height as height

We already implemented this correctly for the width axis, but the
height axis tried to bake min/max constraints into the solve_for
lambda. This corrupted the constraint equation when solving for
height with auto height + min-height, since the height term couldn't
cancel itself out (it was inflated to min-height on subtraction but
stayed 0 on addition).

This caused abspos elements with top+bottom insets and min-height to
incorrectly get the min-height as their height, even when the
containing block was tall enough for a larger height.
2026-02-10 11:58:15 +01:00
Aliaksandr Kalenik
b41ed92505 LibWeb: Remove Document.h include from Layout/Viewport.h
Move the inline dom_node() method to Viewport.cpp so the header no
longer needs the full Document definition. Add explicit includes to
files that relied on the transitive dependency.
2026-02-08 18:51:13 +01:00
Jonathan Gamble
ec50525675 LibWeb/Layout: Don't inject natural size in prepare_for_replaced_layout
Instead, compute them on demand. This affects ReplacedBox and its
subclasses.

This commit is centered around a new Box::auto_content_box_size
method. It returns a SizeWithAspectRatio representing the natural
size of a replaced element, or the size derived from attributes
for text input and textarea. These values are used when the
corresponding axis is auto or indefinite.

Although introducing this API choke-point for sizing replaced and
replaced-like elements was the main goal, it's notable that layout
becomes more robust in the face of dynamic changes due to reduced
potential for stale size values (at the cost of extra calculations
and allocations).
2026-02-02 14:36:49 +00:00
Tim Ledbetter
cf208c8e5e LibWeb: Exclude UA internal shadow roots from percentage height quirk 2026-02-02 12:28:05 +00:00
Andreas Kling
640ec0b64e LibWeb: Fix percentage height resolution in quirks mode
The quirks mode percentage height calculation quirk was incorrectly
applied to anonymous boxes (like the internal flex wrapper inside
buttons), causing buttons to collapse to zero height.

Per the quirks spec, the percentage height quirk:
- Only applies to DOM elements, not anonymous boxes
- Does not apply to flex/grid items (they resolve against their
  container)
- Does not apply to table-related display types

This patch:
1. Excludes anonymous boxes and flex/grid items from the quirk in
   should_treat_height_as_auto()
2. Adds quirks mode percentage height walk-up in
   calculate_inner_height() for inline-level boxes
3. Removes the incorrect flex/grid container exclusion from
   BlockFormattingContext (the quirk applies to containers, not items)
2026-01-26 16:48:21 +01:00
Andreas Kling
492629e3d8 LibWeb: Don't resolve percentage heights against min-height
Per CSS 2.1 Section 10.5, percentage heights should only resolve when
the containing block's height is "specified explicitly". This means a
containing block with `height: auto` and `min-height: 50px` does NOT
provide a definite height for percentage resolution - the child's
`height: 100%` should be treated as `auto`.

Previously, we checked `available_space.height.is_indefinite()` to
determine if percentage heights should become auto. However, this
conflated "available layout space" with "containing block height for
percentage resolution" - these are distinct concepts.

Now we check the containing block's `has_definite_height()` flag, which
correctly reflects whether the containing block has an explicit height
property. This handles:

- Anonymous wrapper blocks (skip them to find real containing block)
- Quirks mode (has special percentage height handling)
- Absolutely positioned elements (excluded, different rules apply)

Also update `calculate_inner_height()` to use the containing block's
actual used height when resolving percentages with indefinite available
space, which fixes inline-block and similar cases.
2026-01-25 20:29:44 +01:00
Jelle Raaijmakers
6a29b8cc03 LibWeb: Derive inline-block baseline from nested content
Compute inline-block baselines by traversing into nested block children
to find the last in-flow line box, using correct offsets relative to the
margin box edge.

Also ensure inline-flex and inline-grid containers always derive their
baseline from content (per CSS Align), and add special handling for
<input> elements which have `overflow: clip` in the UA stylesheet but
should still align adjacent text with their internal content.
2026-01-22 19:36:09 +01:00
Andreas Kling
dc79259970 LibWeb: Support inline elements as abspos containing blocks
CSS allows inline elements with `position: relative` (or other
containing-block-establishing properties) to serve as the containing
block for their absolutely positioned descendants. However, our layout
system stores containing blocks as `Box*`, which cannot represent
inline elements (they are `InlineNode`, not `Box`).

This patch adds a workaround: when computing containing blocks, we
also check if there's an inline element between the abspos element
and its Box containing block that should actually be the CSS
containing block. If found, we store it in a new member called
`m_inline_containing_block_if_applicable` and use it during abspos
layout to:

1. Compute the inline's fragment bounding box as the containing
   block rectangle (including padding, per CSS spec)
2. Resolve percentage-based insets against the inline's dimensions
3. Position the abspos element relative to the inline's location

Some details to be aware of:

- The inline containing block search happens in the function
  `recompute_containing_block()` by walking DOM ancestors (not layout
  tree ancestors, since the layout tree restructures blocks inside
  inlines as siblings)

- For pseudo-elements like `::after`, we start the search from the
  generating element itself, since it may be the inline containing
  block

- Fragment offsets are relative to their block container, so we
  translate the computed rect to the abspos element's containing
  block coordinate system by accumulating offsets up the ancestor
  chain

- When the abspos element uses static position (auto insets), we
  don't apply the inline rect translation since static position is
  already computed in the correct coordinate system

Long term, we want to refactor our "containing block" concept to
map more cleanly to the spec concept. That means turning it into
a rectangle instead of the box this rectangle was derived from.
That's an invasive change for another day though.
2026-01-19 17:34:46 +01:00
Andreas Kling
9079e2b4a7 LibWeb: Return 0 for intrinsic sizes of childless boxes
Boxes with no layout children have no content, so their intrinsic
content size is zero by definition. This lets us skip creating a
throwaway layout state and running a formatting context just to
arrive at the same answer.
2026-01-14 11:46:23 +01:00
Psychpsyo
5be1e9076a LibWeb: Fix crash when abspos element is relative to table row
This occured because the abspos containing block is in-between the
containing blocks of two regular ancestors in this case, so it was
being skipped. (The containing block of a table cell is the table
itself, not the table row.)
2025-12-17 11:59:46 +01:00
Psychpsyo
3760818d58 LibWeb: Implement CSS-Multicol's 'Pseudo-Algorithm' 2025-12-15 09:45:48 +00:00
Jelle Raaijmakers
f9b4fa9702 LibWeb: Add CSS::Size::is_intrinsic_sizing_constraint() 2025-11-05 12:01:40 +01:00
ayeteadoe
30729feebb LibWeb: Prevent crash in content calculations for ListItemMarkerBox
In several content calculation methods in FormattingContext, we assumed
that if create_independent_formatting_context_if_needed() fails the
input Layout::Box is a BlockContainer; however, the web platform test
css/css-pseudo/parsing/marker-supported-properties-in-animation.html is
one scenario where the input is a Layout::ListItemMarkerBox instead and
there is no FormattingContext supported for it yet.
2025-10-30 18:21:24 +00:00
InvalidUsernameException
1ffb0ca311 LibWeb: Remove redundant function parameter
This function can really only be called with a box and its containing
block, otherwise the results are not meaningful. Instead of passing
these two dependent values separatly, reduce it down to a single
parameter to not make the function appear more general than it is.
2025-10-14 10:23:27 +02:00
InvalidUsernameException
70c46e081d LibWeb: Correctly calculate nested positioned elements' static position
If there are multiple nested `position: fixed` or `position: absolute`
elements that are positioned based on their static position due to not
specifying any insets, we sum up all their ancestor offsets to calculate
said static position.

However, these offsets represent the offset to the containing block. So
summing up all the ancestor blocks will count elements multiple times
for cases where the containing block is not based on the closest element
capable of forming a containing block (i.e. absolute and fixed position
elements) when multiple such elements are nested.

With this change we only iterate over ancestors forming containing
blocks instead of over all ancestors boxes. To sum up everything between
the box currently being positioned and its containing block, we start
the iteration on the parent box of the current box.

This fixes 3 WPT tests that I could find. But these tests are not
intended to test the error cases fixed here, they just incidentally rely
on the correct behavior. As such, I have added dedicated tests myself.
Note that two of the tests already pass on master, but they seemed like
a good cases to have anyway.
2025-10-14 10:23:27 +02:00
=
a3e973970a LibWeb/CSS: Check overflow value before determining box baseline
The CSS spec says the baseline of an inline-block should be the bottom
margin when either the overflow property is not 'visible' or there are
no in-flow line boxes. Previously, only the latter case was checked.

This fixes 1 WPT test:
https://wpt.live/css/css-align/baseline-of-scrollable-1a.html
2025-10-13 09:47:32 +01:00
Andreas Kling
f00f975cf4 LibWeb: Treat percentage max-width as none during min-content sizing
...but only for non-replaced boxes. This is what CSS-SIZING-3 tells us
to do, and we were already doing it for width, but neglecting max-width.
2025-09-28 19:25:18 +02:00
Andreas Kling
4b281fa880 LibWeb: Make Length ctor/dtor/factory inline
These functions are trivial, and we were actually bleeding a lot of time
in profiles to just function entry/exit.

By marking Length::make_px() as [[nodiscard]], we also exposed some
places that were creating a Length and not using it for anything.
2025-09-24 23:59:41 +02:00
zac
191b026c9f LibWeb: Rename is_generated to is_generated_for_pseudo_element
While much longer, this better conveys the intent. Since this method
isn't used too often, I think the extra length is worth it.
2025-09-24 12:33:17 +01:00
Callum Law
405c5ffa60 LibWeb: Propagate border-box dimensions when getting max content width
This means that we now calculate the inner width correctly for `display:
inline-block` nodes when we have `box-sizing: border-box` and
`min-width`, as we would previously assume these dimensions were all `0`
2025-09-10 11:41:30 +02:00
Sam Atkins
dd122e2f74 LibWeb: Make LengthBox hold LengthPercentageOrAuto
Not every user of this requires an `auto` state, but most do.

This has quite a big diff but most of that is mechanical:
LengthPercentageOrAuto has `resolved_or_auto()` instead of `resolved()`,
and `to_px_or_zero()` instead of `to_px()`, to make their output
clearer.
2025-09-04 13:31:24 +01:00
Sam Atkins
80310b5ebf LibWeb/Layout: Use LengthOrAuto in abspos non-replaced width computation 2025-09-04 13:31:24 +01:00
Luke Wilde
b17783bb10 Everywhere: Change west consts caught by clang-format-21 to east consts 2025-08-29 18:18:55 +01:00
Tim Ledbetter
cb1a1a5cb5 LibWeb: Replace is<T>() with as_if<T>() where possible 2025-08-25 18:45:00 +02:00
Jelle Raaijmakers
087601832a LibWeb: Set fit-content width for buttons in used values, not computed
For button layouts, we were overriding the computed `width` value with
`fit-content` in `TreeBuilder::wrap_in_button_layout_if_needed()`. But
the spec asks us to set the _used value_ instead, so we now actually
calculate the fit-content width and set the box' content width to it.

Fixes #2516.
2025-08-18 11:04:34 +01:00
Aliaksandr Kalenik
4d223462a5 LibWeb: Fix cyclic percentage resolution in calculate_min_content_width
Brings back some code removed in 652a457, but this time with explanation
from https://www.w3.org/TR/css-sizing-3 spec.
2025-08-13 10:14:37 +01:00
Aliaksandr Kalenik
652a457f52 LibWeb: Fix grid layout for replaced items with percentage max-width
CSS grid specification states that for grid items with a replaced
element and a percentage preferred size or maximum size, the percentage
should be resolved against 0 during content-based minimum size
calculation. This makes sense, as it prevents replaced items from
overshooting their grid track while intrinsic track sizes are
calculated, and allows later track size resolution steps to scale
replaced items to fit their grid track.
2025-08-10 11:07:02 +02:00
Andreas Kling
41e8211405 LibWeb: Honor "should treat as auto" cases in aspect-ratio decisions 2025-08-05 21:33:41 +02:00
Timothy Flynn
8b6e3cb735 LibWeb+LibUnicode+WebContent: Port DOM:CharacterData to UTF-16
This replaces the underlying storage of CharacterData with Utf16String
and deals with the fallout.
2025-07-24 19:00:20 +02:00
Andreas Kling
8d02f28cc2 LibWeb: Don't treat non-replaced sizes as 0 for min-content contrib
This behavior is part of the cyclic percentage contribution logic from
CSS-SIZING-3 which explicitly only applies to non-replaced boxes.

This fixes an issue on Discord where buttons in the settings UI were
cropped to a narrower width than intended.

Fixes #3572
2025-07-23 19:52:59 +02:00
Michael Manganiello
89036dd70c LibWeb: Fix size computation for elements with max-width and max-height
The specification [1] indicates that the tentative used width and height
should be computed first, and if they exceed the `max-width` or
`max-height`, the rules should be applied again using the computed
values of `max-width` and `max-height`.

The only required change to follow the spec is to remove the early
`return` statements, in both `compute_width_for_replaced_element`
and `compute_height_for_replaced_element`.

Fixes #5100.

[1] https://www.w3.org/TR/CSS22/visudet.html#min-max-widths
2025-07-20 17:34:19 +02:00