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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With