Work around for page-break-inside:avoid

2019-04-12 20:38发布

I am currently working on printing something. I have a dynamic page where it has variable numbers of block level elements. Some may be 1 line, and some may be 100+ lines.

<div class='myclass'><span id="id1">1</span>text 1 line....</span></div>
<div class='myclass'><span id="id2">2</span>text 10 lines....</span></div>
<div class='myclass'><span id="id3">3</span>text 3 lines....</span></div>
<div class='myclass'><span id="id4">4</span>text 100+ lines....</span></div>
...

I know the page-break-inside:avoid; when it is implemented (supported by Opera, Chrome, and IE7+ in strict html mode only) suppose to prevent a block level element wrapping around 2 pages. Since this css tag is not support across browsers I am wondering if there are any work around yet?

I have attempted to use jquery, post rendering, and measure each of the element per page, adding up the height, and when the last element added up to be greater than the page height, i add a page-break-before:always to that element, but that only work if I assume a certain page size, and that is never a good assumption.

sudo code only
document.ready(function(){
  var pagesize = 100;
  var currentheight;
  $('.myclass').each(function(){
    if (currentheight + this.getHeight() > pagesize || this.getHeight > pagesize) {
      this.css('page-break-before', 'always');
      currentheight = this.getHeight() % pagesize;
    }
  });
});

And I don't want to just add page-break-before / after :always to every element because doesn't make sense to have a 1 liner on a single page.

2条回答
干净又极端
2楼-- · 2019-04-12 20:54

Try.myclass{page-break-before: auto;}

查看更多
迷人小祖宗
3楼-- · 2019-04-12 20:58
.keep-together {
        page-break-inside: avoid;
   }

add your style. Then add keep-together class in every section.

查看更多
登录 后发表回答