Units and measurement / px in a paged context
How many pixels wide is an A4 page in a PDF
CSS defines one inch as 96 pixels, so A4 at 210mm wide is 793.7 pixels. The fraction is the reason pixel-based page layouts drift.
What it is for
Every layout inherited from a web design is in pixels, and the conversion is what decides whether that layout fits the page or overflows it by a hair.
Support: Works everywhere
The conversion is fixed by the specification, so it is the same everywhere. What varies is what happens to the fractional part, which is why 794px is sometimes one pixel too wide.
The syntax
Written the way it would appear in a document stylesheet, using px in a paged context as intended.
/* The numbers, for reference:
A4 210mm x 297mm = 793.7px x 1122.5px
Letter 216mm x 279mm = 816px x 1056px
A5 148mm x 210mm = 559.4px x 793.7px
4x6 101.6mm x 152.4mm = 384px x 576px
Rather than converting, express the layout in the units the paper uses: */
.document {
width: 178mm; /* not 673px */
}The mistake people make
Setting a container to 794px for A4. The real width is 793.7px, so the container is fractionally wider than the page and the layout overflows by an amount too small to see and large enough to trigger a break.
Frequently asked
Does px in a paged context work when generating a PDF?
Works everywhere. The conversion is fixed by the specification, so it is the same everywhere. What varies is what happens to the fractional part, which is why 794px is sometimes one pixel too wide.
How would I know if it were not working?
You would not, from the CSS. Unimplemented and unmatched CSS both fail silently, which is why the reliable test is to set a deliberately extreme value and see whether anything changes. If a 40mm margin looks the same as an 18mm one, the rule is not reaching the page.
Related properties
Things that come up in the same part of a document stylesheet.
Which CSS units should a PDF use
mm, cm, in, pt. Works everywhere.
What does 100vh mean in a PDF
vh and vw. Works in a browser-based render.
What DPI should images be for a PDF
resolution. Works everywhere.
How to stop an element splitting across PDF pages
break-inside. Works everywhere.
How to force a page break before an element in a PDF
break-before. Works everywhere.
Every property, with its support status
The full reference, grouped by what part of the page it touches.
Paste the CSS and see what the rendered page does with it.