Changing print margins using CSS @page :first causes other pages to cut off text
Asked Answered
S

2

7

I am trying to format a webpage for printing. The first page is a cover page with full bleed background. The rest of the pages have a margin.

@page {
   margin: 2cm;
}
@page :first {
   margin: 0;
}
.cover {
   display: block;
   height: 100%;
   width: 100%;
   background-color: green;
   page-break-after: always;
}

<div class="cover"></div>
<p>HUGE BLOCK OF BODY TEXT...</p>

The first page looks perfect with no margin, but all the remaining pages with the margin have the text cut off.

First page with 0 margin

Inner page with 2cm margin

The problem seems to be the first page. When I comment out the the margin: 0 for the first page, all the remaining pages look correct.

First page with 2cm margins

Inner page with 2cm margins

Is there a correct way to change margins using @page :first that doesn't affect the remaining pages?

Saracen answered 10/8, 2021 at 20:3 Comment(0)
S
1

Took awhile searching but appears that it has come up before as a possible bug with Chrome.

See this other question https://mcmap.net/q/737575/-page-first-margin-in-chrome-bug

The padding solution could work, if you had a container for the content and applied a 2cm padding, however at page-breaks it doesn't apply padding on top or bottom.

Seigel answered 11/8, 2021 at 20:30 Comment(0)
A
1

I ran into the same issue and found some workaround to fix this. In my approach I create wrappers for pages which have at least 1 page height and force every wrapper after first one to have specific max-width. I guess that chrome have bad implementation of calculating width: 100% and base it on the first page margin every time.

CSS:

@page {
  margin: 2cm;
}
@page:first {
  margin: 0;
}
body {
  margin: 0;
}
section.page {
  min-height: 100vh;
  page-break-before: always;
}
section.page--cover {
  background-color: blue;
}
section.page:not(:first-child) {
  /* We need to force page content to not be wider than actual page width */
  max-width: calc(100% - 4cm); /* (first page margin) x 2 */
}

HTML:

<section class="page page--cover">
  first cover page in wrapper (@page margin 0)
</section>
<section class="page">
  second page in wrapper (@page margin 2cm)
  content here can be longer then page height, in this solution 
  page break's should be working fine with given 2cm margins.
</section>
Aggress answered 16/11, 2021 at 17:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.