如何在CSS对齐中消除空白间隙

9
如果我使用
text-align:justify
属性,段落在维持指定宽度时会显示不必要的单词间距。在互联网上搜索,但没有得到任何合适的结果。我也使用了 white-space,但没用。

fiddle :fiddle

2
当您使用“justify”时,您期望什么? - Mr. Alien
左对齐 + 两端对齐的组合 - Sebin Simon
如果它是左对齐的,那么它就不再合理了 :) 另外,我喜欢Mr_Green的解决方案。 - Mr. Alien
连字符属性 hyphens: auto;text-align: justify; 结合使用可以减少(而非消除)空白间隔。此外,您必须为连字符指定 lang 属性才能使其正常工作,而且只有英语在所有浏览器上都有良好的支持。https://developer.mozilla.org/en-US/docs/Web/CSS/hyphens - Wax
2个回答

15

最接近的解决方案是使用word-break: break-all,但这样也会打断单词。如果您可以接受这一点,那么请使用这个解决方案:

.sample_test p{
    word-break: break-all;
}

Fiddle

编辑(2021年11月)

另一个更好的最接近解决方案是使用hyphens: auto。我们必须在HTML元素中提及全局属性lang以使其生效:

.sample_test {
  display: block;
  margin: 0 auto;
  width: 400px;
  height: auto;
}

.sample_test p {
  /* word-break: break-all; */
  hyphens: auto;
}
<div class="sample_test" lang="en">
  <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.</p>
  <p>Contrary to popular belief,.. It has roots in a piece of classical Latin literature from 45 BC,</p>
  <p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum,
    you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary
    of over 200 Latin words,</p>
</div>


9
治疗方法比疾病本身更加严重。 - Jukka K. Korpela
@JukkaK.Korpela “最好的药物总是苦涩的”.. 你应该检查上面的评论。你能否解释一下它有什么问题? - Mr_Green
处理排版问题的方式导致单词随意断裂是荒谬的。 - Jukka K. Korpela
@JukkaK.Korpela 您的观点是正确的,我在我的帖子中也提到了同样的问题。但是,原帖作者对我的回答感到满意...这意味着他对单词分割没有问题。 - Mr_Green
满意并不代表没问题,而你也没有提到这个“解决方案”是荒谬的。 - Jukka K. Korpela
@JukkaK.Korpela,不确定您为什么认为这个解决方案荒谬。word-break: break-all 确实会打断单词,这是已知的事实。我已经通知了 OP,告诉他:“如果你觉得这个方案可以接受,就使用它吧。”我并不是让您退还我的分数,只是想知道除了打断单词之外,这个解决方案有什么问题? - Mr_Green

2
当你使用text-align: justify时,你是在“请求”浏览器添加间距,而浏览器会将此实现为单词之间的额外间距。根据CSS文本模块3级草案,你可以使用text-justify: distribute,要求浏览器在单词之间和单词内字符之间都添加间距,以获得更平衡的结果,但这种效果是否真正更好存在争议,并且此功能仅在IE中实现(很久以前)。
为了改善情况,你可以使用连字号化。这通常减少了添加间距的需要,尽管它当然不能完全消除它。最有效的方法是使用Hyphenator.js,这意味着你需要声明页面的语言,例如<html lang=en>,将hyphenate类设置在任何需要连字号化的元素上,例如使用<body class=hyphenate>来连字号化所有内容,然后只需添加代码。
<script src=http://hyphenator.googlecode.com/svn/tags/Version%204.2.0/Hyphenator.js></script>
<script>Hyphenator.run();</script>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接