html - Stretch text to fit width of div -


i have div fixed width, text inside div can change.

is there way of setting, css or other, spacing between letters text fills div perfectly?

as mark said, text-align:justify; simplest solution. however, short text, won't have effect. following jquery code stretches text width of container.

it calculates space each character , sets letter-spacing accordingly text streches width of container.

if text long fit in container, lets expand next lines , sets text-align:justify; text.

here 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 slong, ugly if displayed on 1 line let me expand several lines , 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


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -