Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; 

This example does not work though these two do

  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.

like image 854
Mark Walsh Avatar asked Mar 04 '13 05:03

Mark Walsh


People also ask

How do you check font size in HTML?

Open the website you want to use. Press Ctrl + Shift + C (Cmd + Shift + C on Mac). Hover over the text to display the font style, size, color code, and margin.

What is font size in HTML?

To allow users to resize the text (in the browser menu), many developers use em instead of pixels. 1em is equal to the current font size. The default text size in browsers is 16px. So, the default size of 1em is 16px.

What is the HTML tag for size?

The HTML <small> element is found within the <body> tag. The <small> tag is used to make the text one size smaller (ie: from x-large to large, large to medium, medium to small). The <small> tag can not make the text smaller than the browser's minimum font size.


2 Answers

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

You should use window.getComputedStyle.

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'; 
like image 168
Paul Armstrong Avatar answered Oct 09 '22 01:10

Paul Armstrong


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.

like image 27
kiranvj Avatar answered Oct 08 '22 23:10

kiranvj