根据内容大小分配列计数属性(CSS问题)

时间:2016-09-01 06:53:46

标签: css

我的页面中有一些段落。有些非常冗长,有些非常小。我为所有段落赋予了column-count : 2的共同属性。但问题是我如果内容仅为两行或三行,则不想将段落拆分为两个

这是我的代码。

p{
	column-count: 2;
}
<h2>First paragraph (needs to be two column)</h2>
<p>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, remaining essentially unchanged. 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.</p>
<h2>Second one (no need of column)</h2>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the </p>

此处我的第一个段落很长且我希望它显示为两列
但我的第二段太小了,而且我不希望列在两列中。

这是最小工作代码的 Demo

注意:我无法预测哪一段会很长,哪一段会很小。它来自服务器。

修改:由于我的实际代码中有超过100个段落,因此我更倾向于仅使用CSS解析(如果可能)

2 个答案:

答案 0 :(得分:2)

您必须使用JavasScript执行此操作。无法根据其样式内容的字数来有条件地启用或禁用CSS。

当然,它不必是客户端上的JS。您也可以在服务器上添加课程short-paragraph

JS

function letterCount(element) {
    return element.textContent.length;
}

function isShort(element) {
    return letterCount(element) < 200;
}

Array.prototype.slice
    .call(document.getElementsByTagName('p')).forEach(paragraph => {
        if (isShort(paragraph)) {
            paragraph.classList.add('short-paragraph')
        }
    });

CSS

p {
    column-count: 2;
}

p.short-paragraph {
  column-count: 1;
}

这是working Fiddle

速度

基于OP的回复,速度可能是一个问题。这是一个快速benchmark,有500段(检查控制台)。我的旧笔记本电脑在5ms内完成,所以它不应该是一个问题。

答案 1 :(得分:0)

&#13;
&#13;
.odd {
  column-count: 1;
}
.even {
  column-count: 2;
}
&#13;
<h2>First paragraph (needs to be two column)</h2>
<p class="even">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, remaining essentially unchanged. 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.</p>
<h2>Second one (no need of column)</h2>
<p class="odd">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the </p>
&#13;
&#13;
&#13;

简单明了,为你的段落创建一个奇数和偶数的类,然后根据自己的喜好进行设计。无论哪个Paragraph你都不想有两列,只需给它们分配奇数类。