page-break-* doesn't work on Chrome and Safari

2020-07-18 11:16发布

I know that there're lots of questions on this topic, but I still could not find a working solution. So, here's my html:

<div class="row">
    <div class="col-xs-12">
      <div class="row print-break">
        <div class="col-xs-8 col-xs-offset-2">
          <!-- Some Content -->
        </div>
      </div>
      <div class="row print-break">
        <div class="col-xs-8 col-xs-offset-2">
          <!-- Some Content -->
        </div>
      </div>
      <div class="row print-break">
        <div class="col-xs-8 col-xs-offset-2">
          <!-- Some Content -->
        </div>
      </div>
    </div>
  </div>

And css:

@media print {
   .print-break {
      page-break-after: always;
      page-break-inside: avoid;
   }
}

And it happens that Firefox insert page breaks properly; Chrome and Safari doesn't.

Do anyone know how to overcome this? Or where am I possibly wrong?

2条回答
一纸荒年 Trace。
2楼-- · 2020-07-18 11:54

Make sure that element with page-break-after: always; has no parents with float property set to other value than none;, also check that it's a block element. If it's inline-block element, it won't apply page break at all.

查看更多
相关推荐>>
3楼-- · 2020-07-18 12:15

Your specific code has a few items of discussion, these individually are correct, but together cause your issue.

Unfortunately page-break-after works differently from browser to browser, one cannot assume a behaviour and we thus need to revert to a simpler, known behaviour.

Some browsers will not page-break on a div with a parent that has a float and/or has a width.

I'm assuming from your code that you're using Bootstrap (?). You have a nested grid in the code: The outer row/col is 12 wide. (Why nest inside a 12-wide parent?) This outer col sets a width: 100%, so Safari will not page-break it's children - so your nested items will not page-break.

I can't tell why you're nesting on a 12-wide, but if you can remove that then your page-break will work.

I personally also page-break in an independent, separator tag (a div or a span) - this makes the code easier to read and I can also style the tag if I wish.

You also don't need to row each row, just a clearfix will 'new row', and this allows us to use that same separator.

An un-nested rewrite of your code thus then works (or it does in my Safari):

<div class="row">
  <div class="col-xs-8 col-xs-offset-2">
    Some Content 1
  </div>
  <div class="print-break clearfix"></div>
  <div class="col-xs-8 col-xs-offset-2">
    Some Content 2
  </div>
  <div class="print-break clearfix"></div>
  <div class="col-xs-8 col-xs-offset-2">
    Some Content 3
  </div>
</div>

And CSS wil be:

@media print {
  .print-break {
    page-break-after: always;
  }
}

(You don't really need @media print - it's superfluous in this context.)

查看更多
登录 后发表回答