Demo and full code is like this : https://jsfiddle.net/oscar11/Ldrntc8x/1/
When I using : nm = 'chelsea chelsea chelsea chelsea chelsea chelsea chelsea';
And : nm = 'iiiii iiiii iiiii iiiii iiiii iiiii iiiii iiiii';
Its width is different
How to keep it the same width?
In some tutorials using css width, but I am confused implementing
You should use a monospace font then.
Eg, add font-family:"Menlo";
(the one Stack Overflow uses for code blocks :)
body{ font-family: Menlo, monospace; }
iiiii iiiii iiiii<br> wkerh werce kjhvg
The only way I would know is to add a monospace
font to your output element:
div {
font-family: monospace;
}
<div class="test">
chelsea chelsea chelsea chelsea chelsea chelsea chelsea
</div>
<div class="test">
iiiii iiiii iiiii iiiii iiiii iiiii iiiii iiiii
</div>
In CSS:
.test {
width: 100px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
I updated your fiddle: https://jsfiddle.net/Lwpv1frd/1/
Remove javascript. I think this can help you. Depends on how you will use it. Cheers!
I saw this posted on another SO post , i think it might help. You can use it with any font you like.
$.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 { background:gold; width:300px; padding: 10px 0; } 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/1.12.4/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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.