Controlling size of image in CSS @page margin boxes

2 weeks ago 19
ARTICLE AD BOX

I've got an HTML page that's destined to be printed. Chrome has supported CSS page margin boxes for a while now so I'm using those.

<html> <head> <style> @page { size: a4; margin-top: 30mm; margin-bottom: 15mm; margin-left: 10mm; margin-right: 10mm; @top-left { content: url("/images/300x50.png"); background-color: thistle; } @top-center { content: ""; background-color: red; } @top-right { content: "First line of text in the header\A Second line of text in the header\A Third line of text in the header"; white-space: pre; background-color: yellow; } } </style> </head> <body> <p>Document content starts here</p> </body> </html>

In the @top-left box, I need a logo image, but at the moment it can be one of about a dozen different images, of all shapes and sizes, with the potential for more to be added regularly, so I need a solution that works no matter what the dimensions/aspect-ratio of the logo image.

(The background-color properties are just so it's easier to see where the margin boxes are while I'm testing; they won't be there on the finished document.)

With a 300 x 50 image, I get this, which is satisfactory

Top of the printed page, with a 300 x 50 image comfortably within the margin box

I don't want the @top-left box to ever extend more than halfway across the page, so I've included an empty @top-center box.

But with a 600 x 100 image, I get this

Top of the printed page, with a 600 x 100 image that gets cropped where it reaches the right-hand edge of the margin box

And with a 300 x 200 image I get this

Top of the printed page, with a 300 x 200 image extending below the top margin, and appearing underneath the main text of the page

If the image is bigger than the margin box, I want to shrink it to fit the box (while maintaining the same aspect ratio, of course). Ideally, I'd like a small amount of padding at the top and bottom of the box so that the image's maximum height is, say 90% of the height of the margin box. I don't mind the image reaching the very edges at the left and right of the box. I've tried padding, margins, max-height, max-width, and object-fit, and they all seem to apply to the box itself rather than to the image.

Read Entire Article