Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: page-break-before, always, except the first time?

I'm trying to create a pretty-print html page. I need to force a page-break, between top-level constructs, so I added a CSS class to the top-level element of each construct, and set page-break-before:always in the CSS for that class. E.g.:

<body>
<div class="prettyprint">
    <div class='toplevel'>
        ...
    </div>
    <div class='toplevel'>
        ...
    </div>
</div>
</body>

.prettyprint .toplevel { page-break-before:always; }

My problem is I get a blank page, before the first top-level element. Which makes perfect sense, considering what page-break-before:always is supposed to do. But I don't want it.

So, one option is to not include the "toplevel" class in the first element, or to provide a new "firsttoplevel" class that doesn't set page-break-before:always, and set it for the first top-level element, and then use "toplevel" for all the others. I could do it, easily enough, but it seems like it's violating separation of concerns.

So I was wondering if there was a way to do this in CSS? To set a rule that would apply only to the first "toplevel" child of "prettyprint"?

Any ideas would be appreciated.

like image 278
Jeff Dege Avatar asked Aug 02 '10 19:08

Jeff Dege


2 Answers

See a good description on page breaks at: https://css-tricks.com/almanac/properties/p/page-break/

The following works well on Chrome v56. Create a rule that implements page-break-before:always but suppress that rule when it is applied to the first of it's type.

.print-per-page {
  page-break-before: always;
}

.print-per-page:first-of-type {
  page-break-before: avoid;
}
<div>
  <div class="print-per-page">Page 1</div>
  <div class="print-per-page">Page 2</div>
  <div class="print-per-page">Page 3</div>
</div>
like image 196
Aaron Hudon Avatar answered Sep 21 '22 16:09

Aaron Hudon


:first-child

might work but pretty sure there are issues with IE6, see: http://www.quirksmode.org/css/firstchild.html

edit: doesn't work in IE6, and for newer versions of IE doctype must be used for it to work.

like image 37
Alex Avatar answered Sep 19 '22 16:09

Alex