Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML - word full width

Tags:

html

jquery

css

Is it possible to fit the size of a word (variable) to full width (of a div element)?

Described at this JSFiddle: http://jsfiddle.net/HQ3sQ/2/

ofc

font-size:100%;

won't work - maybe a hack solution?

like image 441
Aaroniker Avatar asked Jun 05 '26 18:06

Aaroniker


2 Answers

Not using just CSS, but you can use a Javascript library like FitText. It will measure the text and adjust it until it fits.

like image 124
GolezTrol Avatar answered Jun 08 '26 08:06

GolezTrol


You can use this jquery snippet :

FIDDLE

It calculates the letter-spacing to apply so the text and stretches it to 100% of the width of the container.

$.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();
    });
});
like image 20
web-tiki Avatar answered Jun 08 '26 09:06

web-tiki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!