How it renders / @media print
Does @media print apply when generating a PDF
The print media type matches when a document is being laid out for a paged medium, which a PDF render is.
What it is for
It is how a single stylesheet serves both the screen and the page. It is also, for a document that is only ever a PDF, unnecessary complexity.
Support: Works everywhere
Applies during a PDF render. Rules inside @media screen do not, which is a common cause of a document arriving unstyled: the stylesheet was written for a screen and correctly excluded itself.
The syntax
Written the way it would appear in a document stylesheet, using @media print as intended.
/* For a shared stylesheet, this is the right tool. */
@media print {
.no-print { display: none; }
a[href^="http"]::after { content: " (" attr(href) ")"; }
}
/* For a template that is only ever rendered to a PDF, skip the query and write
the document styles directly. A media query that always matches is noise. */The mistake people make
A shared stylesheet where the useful rules are inside @media screen. They will not apply, correctly, and the document arrives looking like unstyled HTML.
Frequently asked
Does @media print work when generating a PDF?
Works everywhere. Applies during a PDF render. Rules inside @media screen do not, which is a common cause of a document arriving unstyled: the stylesheet was written for a screen and correctly excluded itself.
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.
How to force background colours to print
print-color-adjust. Works in a browser-based render.
How to stop a PDF rendering in dark mode
prefers-color-scheme. Works everywhere.
Why position: fixed behaves strangely in a PDF
position: fixed. Works in a browser-based render.
Why images look blurry in the PDF
image-rendering. Works everywhere.
How to put a background or watermark on every PDF page
background on body. Works in a browser-based render.
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.