Javascript document font size

How can i get default font size in pixels by using JavaScript or JQuery?

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

9 Answers 9

There are a couple of situations this can be useful-

function getDefaultFontSize(pa)

alert(getDefaultFontSize())

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.

Читайте также:  Org json jsonobject java maven

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

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)

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.

Источник

Style fontSize Property

The fontSize property sets or returns the font size of the text.

Browser Support

Syntax

Return the fontSize property:

Set the fontSize property:

Property Values

Value Description
xx-small
x-small
small
medium
large
x-large
xx-large
Sets the size of the font to different fixed sizes, from xx-small to xx-large
smaller Decreases the font-size by one relative unit
larger Increases the font-size by one relative unit
length Defines the font-size in length units
% Sets the font-size to a % of the parent element’s font size
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit

Technical Details

Default Value: medium
Return Value: A String, representing the font size of the text in the element
CSS Version CSS1

More Examples

Example

A demonstration of possible values:

var listValue = selectTag.options[selectTag.selectedIndex].text;
document.getElementById(«demo»).style.fontSize = listValue;

Example

Return the font size of an element:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

How To Get Font Size in HTML

I was reading a question on here trying to get the font size of a text. The answer they gave was to get the pixel size using a measure method. All i want to be able to do is get the font size value so i can change it. For example:

var x = document.getElementById("foo").style.fontSize; document.getElementById("foo").style.fontSize = x + 1; 
  1. document.getElementById(«foo»).style.fontSize = «larger»;
  2. document.getElementById(«foo»).style.fontSize = «smaller»;

The only problem is that it only changes the size once.

9 Answers 9

Just grabbing the style.fontSize of an element may not work. If the font-size is defined by a stylesheet, this will report «» (empty string).

var el = document.getElementById('foo'); var style = window.getComputedStyle(el, null).getPropertyValue('font-size'); var fontSize = parseFloat(style); // now you have a proper float for the font size (yes, it can be a float, not just an integer) el.style.fontSize = (fontSize + 1) + 'px'; 

Note that ‘display’ e.g. will return ‘block’ if that element is ‘block’ even though a parent may have ‘none’ which makes this element invisible. Something like font-size however, will take the value from parents.

If your element don’t have font-size property your code will return empty string. Its not necessary that your element should have font-size property. The element can inherit the properties from parent elements.

In this case you need to find the computed font-size. Try this (not sure about IE)

var computedFontSize = window.getComputedStyle(document.getElementById("foo")).fontSize; console.log(computedFontSize); 

The variable computedFontSize will return with the font size with unit. Unit can be px, em, %. You need to strip out the unit to do an arithmetic operation and assign the new value.

Источник

Style font Property

The font-size and font-family are required. If one of the other values are missing, the default values will be inserted, if any.

The properties above can also be set with separate style properties. The use of separate properties is highly recommended for non-advanced authors for better controllability.

Browser Support

Syntax

object.style.font = «font-style font-variant font-weight font-size/line-height|caption|icon|menu|
message-box|small-caption|status-bar|initial|inherit;»

Property Values

Value Description
style Sets the font-style
variant Sets the text in a small-caps font
weight Sets the boldness of the font
size Sets the size of the font
lineHeight Sets the distance between lines
family Sets the font face
caption The font used for captioned controls (like buttons, drop-downs, etc.)
icon The font used to label icons
menu The font used in menus
message-box The font used in dialog boxes
small-caption The font used in small controls
status-bar The font used in window status bars
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit

Technical Details

Default Value: not specified
Return Value: A String, representing different font properties of the element
CSS Version CSS1

More Examples

Example

Return the font of an element:

Источник

Свойства font-size и line-height

Здесь мы рассмотрим, как соотносятся размеры шрифта и строки, и как их правильно задавать.

font-size и line-height

  • font-size – размер шрифта, в частности, определяющий высоту букв.
  • line-height – высота строки.

Для наглядности посмотрим пример HTML, в котором шрифт и размер строки одинаковы:

Размер шрифта font-size – это абстрактное значение, которое привязано к шрифту, и даётся в типографских целях.

Обычно оно равно расстоянию от самой верхней границы букв до самой нижней, исключая «нижние хвосты» букв, таких как p , g . Как видно из примера выше, при размере строки, равном font-size , строка не будет размером точно «под букву».

В зависимости от шрифта, «хвосты» букв при этом могут вылезать, правые буквы Ё и р в примере выше пересекаются как раз поэтому.

В некоторых особо размашистых шрифтах «хвосты букв» могут быть размером с саму букву, а то и больше. Но это, всё же исключение.

Обычно размер строки делают чуть больше, чем шрифт.

По умолчанию в браузерах используется специальное значение line-height:normal .

Оно означает, что браузер может принимать решение о размере строки самостоятельно. Как правило, оно будет в диапазоне 1.1 — 1.25 , но стандарт не гарантирует этого, он говорит лишь, что оно должно быть «разумным» (дословно – англ. reasonable).

Множитель для line-height

Значение line-height можно указать при помощи px или em , но гораздо лучше – задать его числом.

Значение-число интерпретируется как множитель относительно размера шрифта. Например, значение с множителем line-height: 2 при font-size: 16px будет аналогично line-height: 32px (=16px*2) .

Однако, между множителем и точным значением есть одна существенная разница.

  • Значение, заданное множителем, наследуется и применяется в каждом элементе относительно его размера шрифта. То есть, line-height: 2 означает, что высота строки будет равна удвоенному размеру шрифта, не важно какой шрифт.
  • Значение, заданное в единицах измерения, запоминается и наследуется «как есть». Это означает, что line-height: 32px будет всегда жёстко задавать высоту строки, даже если шрифт во вложенных элементах станет больше или меньше текущего.

Давайте посмотрим, как это выглядит, на примерах:

 
стандартная строка
шрифт в 2 раза больше
шрифт в 2 раза больше

Источник

Оцените статью