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
document.getElementById("foo").style.fontSize = "larger";
document.getElementById("foo").style.fontSize = "smaller";
The only problem is that it only changes the size once.
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.
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.
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.
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';
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With