How do I find the physical length of a string?

On my website, the custom username always appears at the top of every page (along with the site name, other links to pages, etc.) in font size "3"

It took me a very long time to figure it out, but eventually it occurred to me that users with very long usernames were bumping into spacing at the top of every page and all the text is pushed onto a line, making it all look ugly like a sin ( it is only visible to an individual user, since this is their username, but I don't want any of my users to see it at all).

I am not asking how to find the number of characters in their name . I want to know how I can determine the physical amount of space that their name will take and in the event will be too long, reduce the font size to 2 or even if necessary.

The reason simple strlen () will not work is due to potential space differences ("Tragic Dionysus" takes up less space than "HERSHEYFEVER", even though the former has more characters in it).

An extensive Google search constantly leaves me with a lot of character counting methods, so I stayed clueless.

+3


source to share


3 answers


You cannot use PHP for this - because a lot depends on the interface style (font family, font size, font style, etc.). You can use jQuery to determine the length of an element and apply specific functionality as needed:

Html

<span id="box"><?=$yourString?></span> 

      



JQuery

$(function() {
   var box = $('#box');
   if (box.width() >= 50) {
      box.addClass('massiveLength');
   }
});

      

Or, if you want to apply something to all elements, here's a jsFiddle showing you how.

+4


source


In principle, this cannot be done on the server.



Instead, use Javascript to get the actual width of the element, then reduce its font size.

+1


source


I'll just throw this away, but if you close the username block in the element and give it the max width it might solve your problem.

<span style="max-width: 50px; overflow: hidden;">The Username Goes Here</span>

      

0


source







All Articles