Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$.width() returns different results when using custom fonts

Here is the situation:

$(document).ready(function(){
  // this will return different result
  alert($('#foo').width());
  // than this !!!
  setTimeout(function(){
    alert($('#foo').width());
  }, 1000);
});

CSS (in <head> section):

<link href='http://fonts.googleapis.com/css?family=Headland+One' rel='stylesheet' type='text/css'>
... and
#foo {
    font-family: 'Headland One', serif;
}

When i use standard fonts (Arial for example) everything fine (.width() returning same result in both cases)

Is there any workaround different than setTimeout to get proper .width() value and keep custom fonts?

like image 460
Peter Avatar asked Aug 26 '12 19:08

Peter


People also ask

What is font width?

Width is the result of how much horizontal space is taken up by a typeface's characters. A condensed face takes up considerably less space than a wide one.

What is font width CSS?

Set Font Size With Em The default text size in browsers is 16px. So, the default size of 1em is 16px. The size can be calculated from pixels to em using this formula: pixels/16=em.

How do I automatically adjust font size in HTML?

The font-size-adjust property gives you better control of the font size when the first selected font is not available. When a font is not available, the browser uses the second specified font. This could result in a big change for the font size. To prevent this, use the font-size-adjust property.


1 Answers

Since it loads a distant font. You should use $(window).load() rather than $(document).ready() : the first one will be triggered when all the distant fonts / stylesheets / scripts and images have been downloaded, the second one only when the DOM is ready.

like image 172
bperson Avatar answered Oct 22 '22 00:10

bperson