Reputation: 11700
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.
Upvotes: 14
Views: 7718
Reputation: 5839
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>
Upvotes: 10
Reputation: 21
<style>
.prettyprint {
page-break-before: always;
margin-top:0;
}
.prettyprint :first-of-type {
page-break-before: avoid;
}
Upvotes: 2
Reputation: 1609
: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.
Upvotes: 4