LibWeb: Apply contain constraint in default image sizing algorithm

When an image has no intrinsic dimensions but has an intrinsic aspect
ratio, the CSS default sizing algorithm should resolve its size as a
contain constraint against the default object size. Previously, we
returned the default size directly, which caused such images to stretch
to fill the entire background positioning area. The SVG's default
`preserveAspectRatio` would then center the content within that
oversized viewport, making the image appear horizontally mispositioned.
This commit is contained in:
Tim Ledbetter 2026-02-28 19:46:07 +00:00 committed by Jelle Raaijmakers
parent bfef5c460f
commit 80977b5fea
3 changed files with 36 additions and 1 deletions

View file

@ -47,7 +47,18 @@ CSSPixelSize run_default_sizing_algorithm(
// 1. If the object has a natural height or width, its size is resolved as if its natural dimensions were given as the specified size.
if (natural.has_width() || natural.has_height())
return run_default_sizing_algorithm(natural.width, natural.height, natural, default_size);
// FIXME: 2. Otherwise, its size is resolved as a contain constraint against the default object size.
// 2. Otherwise, its size is resolved as a contain constraint against the default object size.
if (natural.has_aspect_ratio() && !natural.aspect_ratio->might_be_saturated()) {
auto aspect_ratio = natural.aspect_ratio.value();
if (default_size.is_empty())
return default_size;
auto default_width = default_size.width().to_double();
auto default_height = default_size.height().to_double();
if (aspect_ratio.to_double() >= default_width / default_height)
return CSSPixelSize { default_size.width(), CSSPixels::nearest_value_for(default_width / aspect_ratio.to_double()) };
return CSSPixelSize { CSSPixels::nearest_value_for(default_height * aspect_ratio.to_double()), default_size.height() };
}
return default_size;
}

View file

@ -0,0 +1,12 @@
<!DOCTYPE html>
<style>
div {
width: 100px;
height: 50px;
background: url(../data/50x50-green.svg) no-repeat;
background-size: 50px 50px;
}
</style>
<div></div>
<!-- FIXME: Workaround to ensure CSS background-image is loaded before taking screenshot: https://github.com/LadybirdBrowser/ladybird/issues/3448 -->
<img style="display: none" src="../data/50x50-green.svg">

View file

@ -0,0 +1,12 @@
<!DOCTYPE html>
<link rel="match" href="../expected/background-size-auto-svg-no-intrinsic-size-ref.html">
<style>
div {
width: 100px;
height: 50px;
background: url(../data/50x50-green.svg) no-repeat;
}
</style>
<div></div>
<!-- FIXME: Workaround to ensure CSS background-image is loaded before taking screenshot: https://github.com/LadybirdBrowser/ladybird/issues/3448 -->
<img style="display: none" src="../data/50x50-green.svg">