Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate total width of text including the left and right bearing

I am trying to calculate the total width of a span in HTML including both the left and right bearings of the first and last characters. I have already tried Javascript's offsetWidth and jQuery's width & outerWidth functions, but neither of them return the correct value I am seeking. Here is an example of what I mean. Running in Firefox the calculated width is 135px, while measuring with the Web Developer plug-in gives an actual width of 141px.

Edit

Here is what I've tried, and here are the values it gives me: offsetWidth = 135 jQuery.width() = 135 jQuery.outerWidth() = 135

None of them are calculating the 6px overhang on the 'f' (which would make the width 141).

like image 858
gyoda Avatar asked Dec 14 '10 16:12

gyoda


1 Answers

Sadly, no straightforward solution exists because it is outside the realm of the box model -- the browser itself does not recognise the overhang of the letter 'f' when rendering layout. You can see this for yourself if you wrap the <span> within a <div> of width: 135px, and overflow: auto -- No scrollbars appear, the overhang is simply cut off. This is also why firebug reports the width without the overhang.

As @Aaron pointed out, the problem doesn't exist with monospaced fonts as no letters extend beyond the character's fixed-width box in those fonts.

The only way to find the real width is through pixel-based (rather than layout-based) methods. I can think of one way: draw the same text, with the same font, onto a <canvas> element, and measure the pixel width that way.

like image 177
David Tang Avatar answered Nov 03 '22 00:11

David Tang