2

is it possible to force table and its first row of content to be on the same page when printing it? This problem arises when there are some other contents preceding the table. The table looks something like the following:

<table>
   <caption>
      Title of the table
   </caption>
   <tbody>
     <tr>first row</tr>
     <tr>second row</tr>
     <---more rows--->
   </tbody>
</table>

Anyone knows how to force the table and its first row (or first few rows) of content to be on the same page when printing? I tried to mask the title and its first few rows with a div (with a height of let's say 200px, and page-break-inside: avoid used), this works but it vertically expands the parent container by 200px (only one table needs masking when i was testing with a dummy webpage) and introduces a blank page.

Jsfiddle for when no masking is applied: https://jsfiddle.net/8pk5L3jz/29/

This is the link to the jsfiddle that describes my problem, the added div.mask causes the container of the table to expand by 200px, so it may potentially results in an empty page (it did in my dummy example): https://jsfiddle.net/8pk5L3jz/26/

TSP
  • 101
  • 1
  • 1
  • 8

1 Answers1

1

this should work :

table caption:first-child{
    page-break-after: avoid;  
}
table tr:first-child{
    page-break-after: avoid;
    page-break-before: avoid;
}
/* for n child */
table tr:nth-child(2),
table tr:nth-child(3){
   page-break-before: avoid;
}

tested with opera

note from MDN doc

Note: this property is in progress of being replaced by the more generic break-after. This new property also handles column and region breaks and is syntactically compatible with page-break-after.

scraaappy
  • 2,830
  • 2
  • 19
  • 29
  • Doesn't seem to work on Jsfiddle and I'm using Chrome – TSP Aug 18 '18 at 23:42
  • it seems that chrome has weird behavior with page-break. The only trick I've found is to add a section tag set to `page-break-inside:avoid;`. It works but it's no more valid HTML. https://jsfiddle.net/scraaappy/s0qov7wm/ – scraaappy Aug 19 '18 at 11:30
  • thanks for the reply, buy it "works" because the section tag wraps all the content (i.e. table and fake content) below the big div, this basically amounts to forcing a page-break-before the table. So this solution doesn't really work. – TSP Aug 19 '18 at 13:25
  • No, if you watch the fiddle,that's not the case. You can create section tag to only wrap elements you're interested in but it crisscross the table, that's why I think it's not valid but it's the behavior you expect – scraaappy Aug 19 '18 at 13:49
  • if u add a border around the section tag, u can tell that it wraps around all the content below the large div. – TSP Aug 19 '18 at 13:58