拉伸文本以适合div的宽度 [英] Stretch text to fit width of div

查看:89
本文介绍了拉伸文本以适合div的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

有一种方法使用css或其他设置,

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

推荐答案

如Mark所说, text-align:justify; 是最简单的解决方案。但是,对于短文本,它不会有任何效果。以下jQuery代码将文本延伸到容器的宽度。

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.

它计算每个字符的空间并设置 letter-spacing

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

如果文本太长,不能容纳在容器中,它允许它扩展到下一行,并为文本设置 text-align:justify;

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.

这里是一个演示:

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

a href =http://jsfiddle.net/webtiki/DPRr9/ =nofollow noreferrer> Js fiddle demo

Js fiddle demo

这篇关于拉伸文本以适合div的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆