In the following code, I am hardcoding the height of a lone div
element to 29.7 cm and the page height to 29.7 cm.
HTML
<html lang="en">
<head>
<title>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div></div>
</body>
</html>
CSS
* {
box-sizing: border-box;
margin: 0;
}
div {
display: inline-block;
border: 0.2cm solid red;
height: 29.7cm;
width: calc(0.5 * 21.0cm);
}
@page {
size: 21.0cm 29.7cm;
margin: 0cm;
}
Why is it that when I print-preview the page on Chrome I get 2 pages instead of 1 page?
2
Answers
You have set the height of your
div
to 29.7cm and also add a border of 0.2cm meaning the total height of the box becomes29.7cm (content) + 0.2cm (top border) + 0.2cm (bottom border)
=30.1cm
.Additionally you have set the page size using @page to 21.0cm by 29.7cm, meaning the maximum height of a single page to be 29.7cm.
Now The total height of the
div
:30.1cm
is slightly larger than thepage height
:29.7cm
, so when the browser prepares to print, it realizes that the content can’t fit on a single page. As a result, the browser splits the content between two pages during the print-preview to make sure everything fits.To prevent this, you need to adjust the height of the
div
so that it fits within the available page height while accounting for the borders and any other elements on the page. This ensures that the content can be displayed on a single page during print-preview.I’ve reduced the height of
div
to 29.3cm which will now add up to29.3cm (content) + 0.2cm (top border) + 0.2cm (bottom border)
=29.7cm
.If you want you can tweak this value. Hope it helped 🙂
You can see the overspill better in Firefox than Edge where the page is simply truncated, and the issue is exacerbated when using different versions or brands of browsers since the underlying conversions often vary depending on content.
I generally have to round SVG outputs downwards more than "normal" divisions
How to ensure it fits is over-ride the metric with pixels
If we save the pre-render from the browser we see from the HTML editor it applied a local style over-ride
Ok so what is needed for FireFox ? and here we see they use a totally different scalar !! so one div height does not fit all browsers in all cases!
Can we use one css for both, yes but beware there be dragons of other differences.