Repository navigation
Support object-fit, object-position and aspect-ratio #604
Description
Part of #552 (step 28, missing support, medium priority).
object-fit, object-position and aspect-ratio are never read.
- An image given both a width and a height is stretched to that box, so logos and product photos in fixed-size slots come out distorted.
- A box given
aspect-ratiokeeps its content height.
Measured on gravitypdf at 60b82630, PHP 8.5.4, from the image's cm matrix and the filled rectangles. The image is tests/data/img/bg.jpg, about 1 : 1.16.
| Rule | Browser | mPDF |
|---|---|---|
<img style="width:60mm;height:20mm;object-fit:cover;object-position:left top"> |
the image scaled to 60 mm wide, cropped to the top 20 mm | stretched to 60 × 20 mm |
object-fit: contain in the same box |
the image 17.2 × 20 mm, centred | stretched |
<img style="width:60mm;aspect-ratio:1/1"> |
60 × 60 mm, stretched: aspect-ratio gives way to the image's own ratio only with auto |
60 × 69.6 mm |
<div style="width:60mm;aspect-ratio:2/1;background:#0f0">ar</div> |
60 × 30 mm | 60 × 5.1 mm |
Cause.
Img::open()readsWIDTH,HEIGHTand themin-/max-values (src/Tag/Img.php:136-141).ImageSizing::fit()(src/Image/ImageSizing.php:26, called atsrc/Tag/Img.php:274) fills in whichever is missing from the image's ratio. When both are given, the image is drawn at exactly that size, with nothing to crop or letterbox it.- Blocks get their height from their content, or from
height.
Fix.
-
object-fitonimg(andsvgdrawn as an image):fillis today's behaviourcontainscales the image to fit inside the boxcoverscales it to cover the boxnonekeeps the natural sizescale-downis the smaller ofnoneandcontain
The box stays the size
widthandheightgive it. The image is drawn at the fitted size and clipped to the content box withre W n, inside theq … Qthe image already has. -
object-position. Place the fitted image in the box: keywords,%and lengths, asbackground-positionis read. The default is50% 50%. -
aspect-ratioonimg. When one ofwidthandheightis given, derive the other from the ratio, not from the image;auto 3/2means the image's own ratio when it has one. -
aspect-ratioon a block. Whenheightisautoand the width is known, set the height from the ratio. Content taller than that grows the box: CSS's automatic minimum size, withmin-height: auto. That is how mPDF treatscss_set_heighttoday. Keep it that way foraspect-ratiowhen A percentageheighton a block resolves against the page area, andheightacts as a minimum thatoverflow: hiddendoes not clip #587 makesheightexact. -
Borders, padding and radius go around the box, not the fitted image, and a radius clips the image.
Tests. Each object-fit value on a wide and a tall image, object-position with keywords, % and lengths, aspect-ratio with only a width, only a height, and neither, a rounded image with cover, and an image in a table cell.
Activity