In web development, adapting to user preferences is crucial for delivering an optimal user experience. This JavaScript function is designed to detect a user’s base font size preference, allowing developers to tailor their web applications accordingly.
The Code
export const getUserFontSizePreference = () => {
const html = document.documentElement;
// Get html computed font-size
const initialFontSize = window.getComputedStyle(html).getPropertyValue('font-size');
// Remove the html font size
html.style.fontSize = 'unset';
// Create & append fake element
const element = document.createElement('div');
element.style.width = '1rem';
element.style.display = 'none';
document.body.append(element);
// Get the size of the fake element
const widthMatch = window.getComputedStyle(element).getPropertyValue('width').match(/\d+/);
// Revert all changes
html.style.fontSize = initialFontSize;
element.remove();
if (!widthMatch || widthMatch.length < 1) {
return null;
}
const result = Number(widthMatch[0]);
return !isNaN(result) ? result : null;
}
How It Operates
The getUserFontSizePreference function assesses the user’s preferred base font size, specifically focusing on rem units. Here’s a breakdown of its operation:
- Initial Setup: The function targets the
<html>element to obtain its computed font size, which serves as the base forremunits. - Measurement Preparation: It unsets the current font size on the
<html>element to avoid any interference with the measurement. - Element Creation: A temporary
<div>element is created with a width of1rem, and is appended to the document body in a non-displaying state. - Measurement: The function retrieves the width of this element in pixels, corresponding to the user’s preferred font size for
1rem. - Cleanup: The original font size is restored, and the temporary element is removed to maintain the integrity of the document.
- Result Extraction: Finally, the function extracts the numeric width and returns it, or
nullif the measurement fails.
Usage Example
Imagine implementing a responsive design that adapts based on user font size preferences. You can use getUserFontSizePreference to dynamically adjust your layout:
const userFontSize = getUserFontSizePreference();
console.log(userFontSize) // example 16
This snippet sets the body font size to match the user’s preference, enhancing readability and accessibility.
Advantages
- Accessibility: Tailoring font sizes to user preferences ensures better readability and a more inclusive experience.
- User Experience: Adapting to user settings can significantly enhance satisfaction and engagement.
- Consistency: Provides a reliable method for determining and applying user-specified font sizes across different environments.
Integrating the getUserFontSizePreference function into your development process can enhance your application’s adaptability to user-specific settings, fostering a more personalized and user-friendly web experience.

Leave a Reply