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 calc开发者_开发知识库ulated 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.
Actually, I think the problem is the font itself. I changed the jsfiddle to font-family: monospace, and it was all contained within the grey box (and calculated correctly, as a result). Even leaving it as the original font, but changing the sample to "aaa" or "mmmm" worked great. It's just the "f" glyph in that font that's blowing it for you.
Unfortunately, I don't know of a DOM attribute that accounts for that. Not sure that's much of an answer, but I don't have access to comment on the question and thought these findings might help point you in the right direction...
How about jQuery's .width()
?
<span id="spanId"> ... </span>
and
var w = $('#spanId').width();
精彩评论