18

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,

1
  • I am surprised to learn there is not a native web API for this! In cases where style needs to depend on font size it is very important. Developers are tempted to override the browser’s default font size and use that, but that is a bad choice for accessibility. Commented Feb 1, 2022 at 15:42

9 Answers 9

22

There are a couple of situations this can be useful-

function getDefaultFontSize(pa){
 pa= pa || document.body;
 var who= document.createElement('div');

 who.style.cssText='display:inline-block; padding:0; line-height:1; position:absolute; visibility:hidden; font-size:1em';

 who.appendChild(document.createTextNode('M'));
 pa.appendChild(who);
 var fs= [who.offsetWidth, who.offsetHeight];
 pa.removeChild(who);
 return fs;
}

alert(getDefaultFontSize())

Sign up to request clarification or add additional context in comments.

3 Comments

The width on this is wrong for me (it's the page width). Changing it from div to span fixes it.
Does it matter that my html element has a font size of 100% (i.e. whatever the browser's settings are), and all other sizes on the website are declared in em? The above code gives me a font size in px, correct? Is this freely interchangeable?
I could find no common web font where the width of an M is 1em. Georgia comes the closest, but the M is still smaller than 1em.
22

It can be done using this line of code:

const fontSize = Number(window.getComputedStyle(document.body).getPropertyValue('font-size').match(/\d+/)[0])
  1. window.getComputedStyle(document.body) - to get all the styles for body
  2. getPropertyValue('font-size') - to get a string value of font-size, example: (16px)
  3. match(/\d+/)[0]) - to get only a number part, example: (16) - string
  4. Number(...) - to convert number part into a number, example: (16) - number

1 Comment

Clearly this should be the accepted answer (the FF had getComputedStyle method since 2009-06-30 - even before the answer from kennebec was written in 2009)
7

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.

The 'em' unit is equal to the computed value of the 'font-size' property of the element on which it is used. The exception is when 'em' occurs in the value of the 'font-size' property itself, in which case it refers to the font size of the parent element. It may be used for vertical or horizontal measurement. (This unit is also sometimes called the quad-width in typographic texts.)

From this documentation the following are true.

  1. Without ancestor magnification, 1em is exactly equal to the pixel font size.

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

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

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

Comments

5

If you use rem as unit the default 'font-size' need take from <html>, not from body or other.

alert(window.getComputedStyle(document.documentElement).getPropertyValue('font-size'))

Comments

3

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.

2 Comments

It sounds like a good idea but i think there is another good solution.
Actually this is pretty much the way it's being done these days.
3

Using jQuery (assuming that you want the font size of a specific element):

var originalFontSize = $('#your_element_id_here').css('font-size');

If you're using Prototype as well as jQuery, you'll want to use the jQuery prefix instead of the dollar sign:

var originalFontSize = jQuery('#your_element_id_here').css('font-size');

This will return the value as a string like so: 16px.

1 Comment

As said: assuming that you want the font size of a specific element. No, no. I just want default font size of current environment.
1

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

Comments

1

This works in FF.

<script>
function getStyle(el,styleProp)
{
    var x = document.getElementById(el);
    if (x.currentStyle)
        var y = x.currentStyle[styleProp];
    else if (window.getComputedStyle)
        var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
    return y;
}

function GetSt()
{
    var font_size = getStyle("div2","fontSize"); 
    alert ( font_size );
}

</script>
<div id="div1" style="height: 100px;font-size: 20px;">
<div id="div2" style="font-size: 2em;">
test
</div>
</div>
<button onclick="GetSt();">Click</button>

2 Comments

+1 for using getComputedStyle()['font-size'] instead of creating a dummy element.
But -1 for using currentStyle which is the proprietary variant for the same getComputedStyle function you +1'd him for :)
1

I think this is what you're looking for:

function getDefaultFontSize () {
// this will return the default* value assigned to the style: fontSize
defsize=(document.body.style.fontSize)
alert('The default font size of your browser is: "' + defsize + '"');
}

*If body has a different fontSize decleration anywhere else in the code (perhaps in some css) the function will return that value. For example:

<style>body{font-size:20px;}</style>
<script>function getDefaultFontSize () {
defsize=(document.body.style.fontSize)
} </script>

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

1 Comment

The style object property of an element only contains those style properties (like font-size, for example) that have been set on the element itself, inline. Meaning that you either have them present in the style attribute as part of element tag, or assign them like style.fontSize=... youself, prior. If your elements get their computed style from say, a linked stylesheet, or a <style>...</style> block in the document, document.body.style contains no useful information. What you are after is the Window.getComputedStyle function. It does exactly what you need above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.