使用CSS或JavaScript自动两列

the*_*int 11 javascript css two-columns

我正在开发一个网站,我的客户希望各种文章的文本分为两列.有点像在报纸上?所以它看起来像:

Today in Wales, someone actually      Nobody was harmed in
did something interesting.            the incident, although one 
Authorities are baffled by this       elderly victim is receiving
development and have arrested the     counselling.
perpetrator.     
Run Code Online (Sandbox Code Playgroud)

[我非常努力想要写出来的东西]

有没有办法只用CSS就可以做到这一点?我宁愿不必使用多个div.我也愿意使用JavaScript,但我真的很糟糕,所以请帮助我们.我想也许JavaScript可以计算内容div中有多少<p>,然后根据它移动它们的后半部分?也许?建议将不胜感激:D

Owe*_*wen 12

好消息是,只有一个CSS解决方案.坏消息是,在现有浏览器中没有任何重大支持.如果它被实现,它将如下所示:

div.multi {
  column-count: 3
  column-gap: 10px;
  column-rule: 1px solid black;      
}
Run Code Online (Sandbox Code Playgroud)

我认为现在你最好的选择可能就是一氧化碳所提到的服务器端

  • 至于2012年春季,CSS解决方案在Firefox/Chrome中运行良好. (2认同)

Mat*_*ley 5

我可能会在你的后端处理它,不管发生了什么.PHP中的示例可能如下所示:

$content = "Today in Wales, someone actually did something...";
// Find the literal halfway point, should be close to the textual halfway point
$pos = int(strlen($content) / 2);
// Find the end of the nearest word
while ($content[$pos] != " ") { $pos++; }
// Split into columns based on the word ending.
$column1 = substr($content, 0, $pos);
$column2 = substr($content, $pos+1);
Run Code Online (Sandbox Code Playgroud)

应该可以在JavaScript中使用InnerHTML做类似的事情,但我个人会避免这种情况,因为越来越多的人使用像NoScript这样的插件来禁用JavaScript,直到明确允许x站点,以及其他任何东西,div的和CSS旨在很好地降级.在这种情况下,JavaScript解决方案会严重降级.


Kri*_*ris -1

首先,我不认为只有 css 可以做到这一点,但我希望被证明是错误的。

其次,仅计算段落对您根本没有帮助,您至少需要所有高度并根据该高度计算文本高度的中间位置,但您必须考虑窗口大小调整等。我认为没有是一个相当简单的现成解决方案。不幸的是,我对找到这个问题的完美解决方案持悲观态度,但这是一个有趣的问题。