Home > Web Front-end > CSS Tutorial > How Can I Reliably Get an HTML Element's Font Size?

How Can I Reliably Get an HTML Element's Font Size?

Mary-Kate Olsen
Release: 2024-12-30 21:56:09
Original
126 people have browsed it

How Can I Reliably Get an HTML Element's Font Size?

Determining Font Size in HTML

When attempting to retrieve the font size of an element, the initial idea of accessing style.fontSize might prove insufficient. This is particularly true when the font size is defined externally in a stylesheet, resulting in an empty string when retrieved using this method.

To address this, you can utilize window.getComputedStyle, as illustrated below:

var el = document.getElementById('foo');
var style = window.getComputedStyle(el, null).getPropertyValue('font-size');
var fontSize = parseFloat(style); // Convert the style value to a numeric font size
el.style.fontSize = (fontSize + 1) + 'px'; // Increment the font size by 1
Copy after login

This approach accurately retrieves the font size, even if it's defined in a stylesheet. The resulting fontSize variable can then be used to dynamically adjust the font size of the specified element.

The above is the detailed content of How Can I Reliably Get an HTML Element's Font Size?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template