Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

html - Stretch text to fit width of div

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

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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

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.

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...