Skip to content Skip to sidebar Skip to footer

How Do I Find The Physical Length Of A String?

In my website, the user's username is always displayed at the top of every page (along with the site title, other page links, etc.) in a font size of '3' It took me a really long t

Solution 1:

You cannot use PHP for this - because so much depends on front-end styling (font-families, font-size, font-styling, etc.). You can use jQuery to ascertain the element length, and apply certain functionality if needed:

HTML

<spanid="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.

Solution 2:

It is fundamentally impossible to do this well on the server.

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

Solution 3:

I'm just gonna toss this out, but if you wrap the username block in a an element and give it a max-width, it might solve your problem.

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

Post a Comment for "How Do I Find The Physical Length Of A String?"