如何在多行上均匀平衡文本?

时间:2016-01-19 11:33:53

标签: javascript html css

我想显示一小段文字,可以换成两三行。它是一个高度可视化的元素,为了造型目的,我希望线条的长度尽可能相等,更喜欢一条线而不是两条线。

而不是:

  

这是一个将包装为两个

的文本示例      

行。

我想要这个:

  

这是

的一个例子      

将包装成两行的文本。

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

  

这段文字足够长,几乎不适合两行。它

     

不应包裹三行或更多行,因此不能限制宽度。

有没有办法在纯CSS或可容忍的JavaScript中执行此操作?

8 个答案:

答案 0 :(得分:9)

2016回答:CSS4:

 text-wrap: balance;

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

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

这是demo of balance text

答案 1 :(得分:1)

如果我理解你的要求(如果我这样做,'使用对齐'的一般主题并不完全如此),我认为你不能避免写一点点的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! (我下班后可能会对此进行更多调查......)

你不能在没有渲染的情况下弄清楚宽度的原因是由于可以用它表示的各种字体类型和大小。因此,如果您总是使用精确的字体类型和字体大小,那么您可以编写一个无需渲染它的函数。

答案 2 :(得分:0)

您可以使用像DIV这样的父标签,并使用宽度= 50%的样式。这将使文本更多。

答案 3 :(得分:0)

我担心在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子元素。

答案 4 :(得分:0)

我用text-align:justify创建了一个exmaple,没有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>

答案 5 :(得分:0)

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

HTML:

<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>

CSS:

#center{
  width : 100px;
  text-align : justify;
}

答案 6 :(得分:0)

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

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

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

&#13;
&#13;
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();
});
&#13;
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;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 7 :(得分:-1)

只需缩短包含此文字的元素的宽度。

https://jsfiddle.net/cqmwqgbj/

$scope.params = params;
        $scope.close = function (result,form) {
            if (result == 'Save') {
                var uri = apiMethod + "?accountId=" + $routeParams.accountId;
                $http.post(uri, formToKeyValueListJSON($element))
                    .success(function (data, status, headers, config) {
                        $uibModalInstance.close({status:'Success', data: data}, 500); // close, but give 500ms for bootstrap to animate
                    })
                    .error(function (data, status, headers, config) {
                        $uibModalInstance.close({status:'Fail', data: data},500);
                    });
            }
        };