Seriamus
Seriamus

Reputation: 67

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 time to figure this out, but it eventually came to my attention that the users with really long usernames ended up messing with the spacing at the top of every page and all the text gets pushed down a line, making the whole thing look ugly as sin (it's only visible to the individual user since it's their username, but I don't want any of my users seeing it at all).

I'm not asking how to find the number of characters in their name -- what I want to know is how I can determine the physical amount of space their name will take up and, in the event it will be too long, reduce the font size to 2, or even 1 if necessary.

The reason why a simple strlen() wouldn't work is because of the potential space differences ("Tragic Dionysus" takes up less room than "HERSHEYFEVER", regardless that the former has more characters in it).

An extensive Google search continually leaves me with more character counting methods, so I'm left clueless.

Upvotes: 3

Views: 1079

Answers (3)

teynon
teynon

Reputation: 8318

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.

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

Upvotes: 0

hohner
hohner

Reputation: 11588

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

<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.

Upvotes: 4

SLaks
SLaks

Reputation: 888185

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.

Upvotes: 1

Related Questions