【问题标题】:How can I evenly balance text over multiple lines?如何在多行上均匀地平衡文本?
【发布时间】:2016-04-24 20:43:25
【问题描述】:

我想显示一段可以换行到两三行的短文本。它位于一个高度可视化的元素中,出于造型目的,我希望线条的长度尽可能相等,更喜欢一条而不是两条。

而不是这个:

这是一段将自动换行的文本示例

行。

我想要这个:

这是一个例子

将换行为两行的文本。

但我不想限制文本容器的宽度:

此文本足够长,仅能容纳两行。它

不应换行至三行或更多行,因此无宽度限制。

有没有办法在纯 CSS 中或使用可容忍数量的 JavaScript 来做到这一点?

【问题讨论】:

  • 我认为仅使用 css 是不可能的。需要像 JavaScript/JQuery 这样的脚本。
  • 你想如何处理一个长单词就应该换行的情况?
  • 你在文本容器上试过max-width 吗?您实际上尝试过什么?为什么不想限制文本容器?
  • 我正在编写一个简单的 javascript 函数。 . .你对长词有什么计划?应该拆分吗?
  • @Pogrindis:我还没有尝试太多,因为我知道这样做的唯一可靠方法是将文本拆分为 span 元素,计算它们的宽度并在需要的地方手动添加换行符屏幕调整大小。我想我会先问一下是否有更简单的解决方案。 @Bit:不需要对长词进行特殊处理。请注意,字体是可变宽度的,所以我们不知道它们最终会在屏幕上显示多宽。

标签: javascript html css


【解决方案1】:

CSS 文本模块 4 属性:

 text-wrap: balance;

会这样做。 https://drafts.csswg.org/css-text-4/#text-wrap

还有a package 为现有浏览器实现了一个polyfill。

这是demo of balance text

【讨论】:

【解决方案2】:

如果我理解你的问题(如果我理解了,'use justify' 的一般主题并不能完全做到这一点),我认为你将无法避免编写相当多的JavaScript。

我能看到做你要求的唯一方法是将文本的宽度与容器的宽度进行比较,并进行相应的调整。

公式:单行宽度=文字宽度/roundUp(文字宽度/容器宽度)

即(可能需要进行一些调整以防止将单词切成两半)

var widthOfText = functionToGetWidthOfText(width); //==120
var widthOfContainer = container.width(); //==100
var containerWidth = widthOfText / ceil(widthOfText/widthOfContainer);
// containerWidth = 120 / ceil(120/100) == 120 / 2 == 60
var formattingTextContainer.width = containerWidth
// text would go inside the formattingTextContainer, which would
// give you 2 lines of equal, 60px width

但是,这样做的问题是,制作了一个“functionToGetWidthOfText”。经过一番快速搜索,我找到的只是this stack overflow question,答案是……

在 span 中包装文本并使用 jquery width()

即把它放在一个元素中并测量它的宽度......你也许可以在屏幕外的某个地方做那个/在足够快的没有人看到它之后删除它,但这可能需要相当多的 JavaScript 行! (下班后我可能会对此进行更多调查......)

您无法在不渲染的情况下计算出宽度的原因是它可以用各种字体类型和大小来表示。因此,如果您始终使用精确的字体类型和字体大小,您也许可以编写一个函数来执行此操作而无需渲染它。

【讨论】:

  • 是的,看来您正确理解了我的问题。 :) 如果没有更简单的解决方案,您的伪代码示例看起来是一个合理的起点。
【解决方案3】:

由于似乎没有现成的解决方案,我编写了一个相对简单的 jQuery 函数来做我想做的事。这是以防其他人正在寻找。

它通过克隆我们想要调整的元素来工作。克隆被隐藏以防止它在注入 DOM 时闪烁。然后,我们一次使克隆变窄一个像素,直到它必须换行。然后将发生此之前的宽度设置为原始元素并删除克隆元素。

我们仍然欢迎更好的方法来实现这一目标,以及改进这一方法的建议。 Codepen 可在此处获得:http://codepen.io/Kaivosukeltaja/pen/jWYqZN

function adjust() {
  $('.quote').each(function() {
    // Create an invisible clone of the element
    var clone = $(this).clone().css({
      visibility: 'hidden',
      width: 'auto'
    }).appendTo($(this).parent());
    
    // Get the bigger width of the two elements to be our starting point
    var goodWidth = Math.max($(this).width(), $(clone).width());
    var testedWidth = goodWidth;
    var initialHeight = $(clone).height();

    // Make the clone narrower until it wraps again, causing height to increase
    while($(clone).height() == initialHeight && testedWidth > 0) {
      goodWidth = testedWidth;
      testedWidth--;
      $(clone).width(testedWidth);
    }

    // Set original element's width to last one before wrap
    $(this).width(goodWidth);
    
    // Remove the clone element
    $(clone).remove();
  });
}

$(window).resize(adjust);
$(document).ready(function() {
  adjust();
});
body {
  background-color: #f0f0f0;
}

.holder {
  text-align: center;
  margin: 2em auto;
}
.quote {
  display: inline-block;
  border: 1px solid #c0c0c0;
  background-color: #fff;
  padding: 1em;
  font-size: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="holder">
  <div class="quote">
    If I want text to wrap, I want the lines as close to equal length as possible.
  </div>
</div>

【讨论】:

    【解决方案4】:

    我创建了一个带有 text-align: justify 和没有 text-align: justify 的示例。

    看看:

        .center {width:200px; float:left; margin-left: 20px;}
        .justify { text-align: justify; }
          
     
        <!-- 4. -->
        <section class="center">
          <p class="justify">orem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
        </section>
        <section class="center">
          <p class="">orem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
        </section>

    【讨论】:

    • 尝试删除第一段中consectetur之后的所有内容。我希望这些线的长度接近相等,但 consectetur 却独自留在自己的线上。
    • 好的,现在我明白你的问题了。没有那么容易。我认为纯 CSS 是不可能的。原因是CSS需要计算字符串的中间来把它切成两半。
    【解决方案5】:

    您可以使用像 DIV 这样的父标签和宽度=50% 的样式。这会使文本的行数更多。

    【讨论】:

      【解决方案6】:

      恐怕在 CSS 中没有办法做到这一点,所以我只是搜索它并 在这里找到它split-large-string-in-n-size-chunks-in-javascriptcounting-words-in-string

      我将把它当作一个挑战,并为它编写一个函数:)

      尝试正则表达式单词的数量并找到其中一半的长度然后这个:

      function chunkString(str, length) {
        length = length/2;
        return str.match(new RegExp('.{1,' + length + '}', 'g'));
      }
      

      .....

      text-align: justify。 我不确定我的问题是否正确,但看看你的声誉,我害怕回答这个问题!! :)

      将文本放在 p 或 span 中,确保它是 display: blockinline-block 也可以。每个元素的宽度应该是父元素的 50%。然后text-align: justify 子元素。

      【讨论】:

      • 我正在考虑提供一个 javascript 函数来包装这个......但是#看着他的声誉我也很害怕。
      • 哈哈哈,这里也一样,但这是 css 中的一件简单的事情,我想知道我的问题是否正确! :) text justify 已经存在多年了!
      • 被名声吓倒是没有意义的,没有人知道一切。
      • 没错,零需要被声誉吓倒。我见过声誉超过 10k 的人就他们以前不熟悉的主题提出非常基本的问题。不幸的是,我无法限制文本宽度,请参阅我更新的第三个示例以了解原因。
      【解决方案7】:

      您可以将文本放入 div 并同时使用 width 和 text-align css 属性:

      #center{
        width : 100px;
        text-align : justify;
      }
      <div id="center">This is an example of a piece of text that will wrap to two lines.This is an example of a piece of text that will wrap to two
      lines.</div>

      【讨论】:

        【解决方案8】:

        只需缩短包含此文本的元素的宽度:

        div {
            width: 210px;
        }
        &lt;div&gt;This is an example of a piece of text that will wrap to two lines.&lt;/div&gt;

        【讨论】:

        • 查看失败示例 - 行应该是等宽或单行:jsfiddle.net/cqmwqgbj/3
        • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
        猜你喜欢
        • 1970-01-01
        • 2019-05-18
        • 1970-01-01
        • 1970-01-01
        • 2016-05-17
        • 1970-01-01
        • 2020-09-07
        • 1970-01-01
        • 2023-03-15
        相关资源
        最近更新 更多