As you know em is a relative font measurement where one em is equal to the height of the letter "M" in the default font size. An advantage in using it is because you will be able to resize the text.
But how can i get default font size of current environment (in pixels) by using JavaScript or JQuery ?
regards,
I think this is what you're looking for:
*If body has a different fontSize decleration anywhere else in the code (perhaps in some css) the function will return that value. For example:
The above will return a fontSize value of 20px.
Fully tested and works for me (chrome 22.0.1229.94 m and firefox 13.01).
I believe the M-principle is a myth. At the very least the following documentation from http://www.w3.org/TR/CSS21/syndata.html proves that calculations based on the M-principle are overly complicated and unnecessary.
From this documentation the following are true.
Without ancestor magnification, 1em is exactly equal to the pixel font size.
Since ancestor magnification with ems and percent works in well defined ways a simple loop will calculate exact font sizes, assuming: no C.S.S; and some ancestor has it's font size set in absolute units.
Since ems measure width you can always compute the exact pixel font size by creating a div that is 1000 ems long and dividing its client-Width property by 1000. I seem to recall ems are truncated to the nearest thousandth, so you need 1000 ems to avoid an erroneous truncation of the pixel result.
You probably can create a font where the M-principle fails since em is based on the font-size attribute not on the actual font. Suppose you have a weird font where M is 1/3 the size of the other characters and you have a font size of 10 pixels. I kind of think the font-size is a guarantee of maximal character height and so the M will not be 10 pixels and all other characters 30 pixels.
It can be done using this line of code:
window.getComputedStyle(document.body)
- to get all the styles for bodygetPropertyValue('font-size')
- to get a string value of font-size, example: (16px)match(/\d+/)[0])
- to get only a number part, example: (16) - stringNumber(...)
- to convert number part into a number, example: (16) - numberAlthough it seems like getting the default font size might be a good idea -- if it's to set the layout of your pages and such, it's probably a safer practice to just let the user handle that.
If they have their font size larger - it's because they're blind and vice versa. I'd recommend setting your defaults and 'recommending' a resolution/size. Unless your app depends on it -- let the user handle it.
There are a couple of situations this can be useful-
alert(getDefaultFontSize())
One trick I've seen/used in the past is to render some text (say 50 arbitrary characters, or Ms) and then measure the size of the rendered container and do the math to figure out the height and width of a single character. Is this what you're going for? You can do the rendering in the background so the user doesn't see it.