首页 > 解决方案 > 使用 css 避免在标题和前几句文本上打断

问题描述

我在它下面有一个标题和一个文本块。我希望标题和前三个句子使用 css 属性来避免分页符page-break-inner: avoid。然后我希望其余的句子像往常一样继续。

我编写了以下代码,但前 3 句之后的句子开始换行,因为我已将包含标题和前三个句子的跨度设置为display: inline-block. 我会将跨度设置为display: inline但我在某处读到了page-break-inside不适用于内联元素的地方。

.avoid-break {
  page-break-inside: avoid;
}

span.avoid-break {
  display: inline-block;
}
<span class="avoid-break">
  <div>Subtite</div>
  <span>
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting.
  </span>
</span>
<span>
  This should continue on the line above! It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</span>

标签: htmlcss

解决方案


一个CSS解决方案:

remove span.avaoid-break

这对于显示的代码非常具体,我不会在生产环境中使用它。

var spans = document.getElementsByTagName('span');
spans[1].innerHTML += spans[2].innerHTML
spans[2].remove()

ID 将使这更有用:

<span class="avoid-break">
  <div>Subtite</div>
  <span id="text-box">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting.
  </span>
</span>
<span id="extra-text">
  This should continue on the line above! It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</span>

Javascript:

var textbox = document.getElementById('text-box');
var extratext = document.getElementById('extra-text');
textbox.innerHTML += extratext.innerHTML;
extratext.remove()

推荐阅读