Html 拉伸文本以适应 div 的宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5976289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 08:33:44  来源:igfitidea点击:

Stretch text to fit width of div

htmlcss

提问by Curt

I have a div with a fixed width, but the text inside the div can change.

我有一个固定宽度的 div,但 div 内的文本可以改变。

Is there a way of setting, with css or other, the spacing between the lettersso the text always fills the div perfectly?

有没有办法用 css 或其他方式设置字母之间的间距,以便文本始终完美地填充 div?

回答by web-tiki

As Mark said, text-align:justify;is the simplest solution. However, for short text, it won't have any effect. The following jQuery code stretches the text to the width of the container.

正如马克所说,text-align:justify;是最简单的解决方案。但是,对于短文本,它不会产生任何影响。以下 jQuery 代码将文本拉伸到容器的宽度。

It calculates the space for each character and sets letter-spacingaccordingly so the text streches to the width of the container.

它计算每个字符的空间并进行相应设置letter-spacing,使文本拉伸到容器的宽度

If the text is too long to fit in the container, it lets it expand to the next lines and sets text-align:justify;to the text.

如果文本太长而无法放入容器中,它会让它扩展到下一行并设置text-align:justify;为文本。

Here is a demo :

这是一个演示:

$.fn.strech_text = function(){
    var elmt          = $(this),
        cont_width    = elmt.width(),
        txt           = elmt.html(),
        one_line      = $('<span class="stretch_it">' + txt + '</span>'),
        nb_char       = elmt.text().length,
        spacing       = cont_width/nb_char,
        txt_width;
    
    elmt.html(one_line);
    txt_width = one_line.width();
    
    if (txt_width < cont_width){
        var  char_width     = txt_width/nb_char,
             ltr_spacing    = spacing - char_width + (spacing - char_width)/nb_char ; 
  
        one_line.css({'letter-spacing': ltr_spacing});
    } else {
        one_line.contents().unwrap();
        elmt.addClass('justify');
    }
};


$(document).ready(function () {
    $('.stretch').each(function(){
        $(this).strech_text();
    });
});
p { width:300px; padding: 10px 0;background:gold;}
a{text-decoration:none;}

.stretch_it{ white-space: nowrap; }
.justify{ text-align:justify; }

.one{font-size:10px;}
.two{font-size:20px;}
.three{font-size:30px;}
.four{font-size:40px;}
.arial{font-family:arial;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="stretch one">Stretch me</p>
<p class="stretch two">Stretch me</p>
<p class="stretch three">Stretch <a href="#">link</a></p>
<p class="stretch two">I am too slong, an I would look ugly if I was displayed on one line so let me expand to several lines and justify me.</p>
<p  class="stretch arial one">Stretch me</p>
<p class="stretch arial three">Stretch me</p>
<p class="stretch arial four">Stretch me</p>
<p class="arial two">Don't stretch me</p>

Js fiddle demo

Js小提琴演示

回答by Aakil Fernandes

This can be done with text-align:justifyand a small hack. See here:

这可以通过text-align:justify一个小技巧来完成。看这里:

div{
  background-color:gold;
  text-align:justify;
}

span{
  background-color:red;
  width:100%;
  height:1em;
  display:inline-block;
}
<div>
  Lorem ipsum sit dolor
  <span> </span>
</div>

The trick is to add an element after the text that pretends to be really long word. The fake word is actually a spanelement with display:inline-blockand width:100%.

诀窍是在假装是很长的单词的文本之后添加一个元素。假词实际上是一个span带有display:inline-blockand的元素width:100%

In my example the fake word is in red and given a height of 1em, but the hack will work even without it.

在我的例子中,假词是红色的,高度为 1em,但即使没有它,黑客也能工作。

回答by Mark

Maybe this could help:

也许这可以帮助:

text-align:justify;

回答by nathan

Even easier HTML/CSS method would be to use flexbox. It's also immediately responsive. But worth noting SEO won't pick it up if you were to use it as a h1 or something.

更简单的 HTML/CSS 方法是使用 flexbox。它也立即响应。但值得注意的是,如果您将其用作 h1 或其他内容,则 SEO 不会接受它。

HTML:

HTML:

<div class="wrapper">
<div>H</div>
<div>e</div>
<div>l</div>
<div>l</div>
<div>o</div>
<div>&nbsp</div>
<div>W</div>
<div>o</div>
<div>r</div>
<div>l</div>
<div>d</div>

CSS:

CSS:

.wrapper{
  width: 100%;
  text-align: center;
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
  border: 1px solid black;
}

jsfiddle here

jsfiddle在这里

回答by wener

I found a better solution for text shorter than one line, without any extra js or tag, only one class.

对于短于一行的文本,我找到了一个更好的解决方案,没有任何额外的 js 或标签,只有一个类。

.stretch{ 
  /* We got 2rem to stretch */
  width: 5rem;
  /* We know we only got one line */
  height: 1rem;
  
  text-align: justify; 
}
.stretch:after{
    /* used to stretch word */
    content: '';
    width: 100%;
    display: inline-block; 
}
<div class="stretch">你好么</div>
<div class="stretch">你好</div>

回答by saricden

A little late to the party, but for a simple, pure CSS implementation consider using flexbox:

聚会有点晚了,但是对于简单的纯 CSS 实现,请考虑使用flexbox

h1.stretch {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
<h1 class="stretch">
  <span>F</span>
  <span>o</span>
  <span>o</span>
  <span>B</span>
  <span>a</span>
  <span>r</span>
</h1>

Not sure if wrapping each letter in a span(note any element will work) will mess with SEO, but I imagine search engines will strip tags from the innerHTMLof tags used for important markup such as headings, etc. (Someone who knows SEO to confirm?)

不确定将每个字母包装在 a span(注意任何元素都可以)会与 SEO 混淆,但我想搜索引擎会从innerHTML用于重要标记(例如标题等)的标签中剥离标签(知道 SEO 的人来确认? )

回答by KyleM

MARCH 2018If you are landing on this question in a more current time...

2018 年 3 月如果您是在更近的时间回答这个问题...

I was attempting do do what the OP asked about but with a single word and found success with the following:

我试图做 OP 所要求的,但只用一个词,并在以下方面取得了成功:

1.Use a <span>and set css: span { letter-spacing: 0px; display:block}(this makes the element only as wide as the content)

1.使用 a<span>并设置 css: span { letter-spacing: 0px; display:block}(这使得元素只与内容一样宽)

2.On load capture the width of the span let width = $('span').width();

2.在负载上捕获跨度的宽度let width = $('span').width();

3.Capture the length of the span let length = $('span').length;

3.捕获跨度的长度let length = $('span').length;

4.Reset the width of the span to the container $('span').css({'width','100%'});

4.重置span的宽度到容器$('span').css({'width','100%'});

5.Capture the NEW width of the span (or just use the container width) let con = $('span').width();

5.捕获跨度的新宽度(或仅使用容器宽度)let con = $('span').width();

6.Calculate and set the letter spacing to fill the container $('span').css({'letter-spacing':(cont-width)/length})

6.计算并设置字母间距以填充容器$('span').css({'letter-spacing':(cont-width)/length})

Obviously this can be converted to use vanilla js and it is useful even with most font styles including non mono-space fonts.

显然,这可以转换为使用 vanilla js,即使对于大多数字体样式(包括非等宽字体)也很有用。

回答by ronaldtgi

Some of the above answers work well but the text has to wrap with many child div
and it's a lot of extra codes.
The text inside the divshould be clean, so I made it with a help of JS.

上面的一些答案效果很好,但文本必须用许多子div换行,
而且还有很多额外的代码。div
里面的文字应该是干净的,所以我是在 JS 的帮助下制作的。

const words = document.querySelector(".words"),
  wordsArray = words.innerText.split("").map(e => " " == e ? "<div>&nbsp</div>" : "<div>" + e + "</div>");
words.innerHTML = wordsArray.join("");
.words {
  width: 100%;
  text-align: center;
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
}
<div class="words">This is the demo text</div>

回答by tvanc

With the lineclamp moduleI wrote you can accomplish what you want. You set a max number of lines or height you want text to take up and it finds the max font size that will fit in that number of lines, and/or trims text to make it fit.

使用我写的lineclamp 模块,你可以完成你想要的。您设置了您希望文本占据的最大行数或高度,它会找到适合该行数的最大字体大小,和/或修剪文本以使其适合。

import LineClamp from "//unpkg.com/@tvanc/lineclamp/dist/esm.min.js";

const clamp = new LineClamp(document.querySelector("#elementToClamp"), {
  useSoftClamp: true,
  // Set an arbitrarily high max font size. Default min is already 1
  maxFontSize: 10000,
  maxLines: 1
});

// .apply() to apply the clamp now
// .watch() to re-apply if content changes or window resizes
clamp.apply().watch();

Working example: https://codepen.io/tvanc/pen/BaNmVXm

工作示例:https: //codepen.io/tvanc/pen/BaNmVXm



In the question, OP says letter spacing. In a comment, OP says letter spacing orfont size.

在问题中,OP 表示字母间距。在评论中,OP 表示字母间距字体大小。

回答by McTrafik

I think what you're actually looking for is scaling.

我认为您实际上正在寻找的是缩放。

Render your font with some nice-looking resolution that makes sense and then use JS to stretch it to the container by using css transforms:

用一些漂亮的分辨率渲染你的字体,然后使用 JS 通过使用 css 转换将其拉伸到容器:

transform: scale(1.05);

The benefits of this is that your text will always wit, but you run into the problem of it becoming too small to be readable.

这样做的好处是你的文本总是很聪明,但你遇到了它变得太小而无法阅读的问题。

Quick note is that you'll need to make the element you're trying to shrink/expand have absolute position:

请注意,您需要使您尝试缩小/扩展的元素具有绝对位置:

position: absolute;