#2937·WeasyPrint

Nested `@media print` inside `body` not taken into account.

Author: caarmenCreated Sep 26, 2026Updated Sep 27, 2026
Labelsfeature

Looks like @media print inside body is ignored.

In this example, we have a 2cm x 2cm red square, and the goal is to have it in the top left corner, with no margin.

To do this, we need to set the margin to 0 for @media print and body.

This works as expected when body is inside @media print, but not when @media print is inside body.

Both are documented in the mozilla css documentation (as I understand it): https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Nesting/At-rules

Note that both work when printing a PDF from Chrome.

Tested generating the pdf using weasyprint <html file> <pdf file>.

Used weasyprint version 70.0.

Here are the results:

body inside @media print

@media print inside body

Short snippet
css
@media print {
 body {
  margin: 0px;
 }
}
css
body {
 @media print {
  margin: 0px;
 }
}
Full example Click
xml
<!DOCTYPE html>
<html lang="en">
<head>
    <title>This works</title>
    <meta charset="UTF-8">
    <style>
        .myblock {
           background: red;
           width: 4cm;
           height: 4cm;
        }
        @media print {
            @page {
                margin: 0px;
                size: A4 portrait;
            }
            body {
                margin: 0px;
            }
        }
    </style>
</head>

<body>
<div class="myblock">hello</div>
</body>
</html>
Click
xml
<!DOCTYPE html>
<html lang="en">
<head>
    <title>This doesn't work</title>
    <meta charset="UTF-8">
    <style>
        .myblock {
           background: red;
           width: 4cm;
           height: 4cm;
        }
        @media print {
            @page {
                margin: 0px;
                size: A4 portrait;
            }
        }
        body {
            @media print {
                margin: 0px;
            }
        }
    </style>
</head>

<body>
<div class="myblock">hello</div>
</body>
</html>
Result Expected behavior, no margin There's still a 0.2cm margin in the top left
Screenshot of pdf Image Image
Pdf

works.pdf

nowork.pdf