Back to JavaScript
2026-02-208 min read

Dynamic Type (JavaScript)

Learn Dynamic Type (JavaScript) step by step with clear examples and exercises.

Title: Dynamic Type (JavaScript) - A full guide

Why This Matters

In web development, creating an accessible and user-friendly experience is crucial. JavaScript's dynamic type system plays a significant role in achieving this goal by allowing developers to adjust the size of text based on users' preferences or screen sizes. Dynamic Type is especially important for improving accessibility for visually impaired users who may require larger font sizes to comfortably read web content.

The Importance of Accessibility

Ensuring your website is accessible to all users, regardless of their abilities, is essential for providing a positive user experience. By implementing dynamic type, you can cater to the needs of visually impaired users and make your website more inclusive.

Prerequisites

Before diving into dynamic type in JavaScript, it's essential to have a solid understanding of the following concepts:

  1. HTML and CSS basics, including elements like `, , , - , and `.
  2. JavaScript fundamentals such as variables, functions, loops, and conditional statements.
  3. Understanding of the Document Object Model (DOM) and how to manipulate it using JavaScript.
  4. Basic understanding of CSS media queries for responsive design.
  5. Familiarity with HTML5 Doctype declaration and HTML structure.
  6. Knowledge of how to create, append, and style DOM elements in JavaScript.
  7. Understanding of the relationship between parent and child elements in the DOM hierarchy.
  8. Basic understanding of CSS properties like font-size, line-height, and letter-spacing.
  9. Familiarity with browser developer tools for inspecting and manipulating web pages.

Core Concept

In JavaScript, there are two main ways to work with dynamic type: em units and the rem unit.

em Units

The em unit is a relative unit of measurement based on the font size of the parent element. For example, if the parent element's font size is 16 pixels, then 1 em equals 16 pixels. When you increase or decrease the parent element's font size, all child elements with em units will adjust accordingly.

// Example of using em units for dynamic text
const parentElement = document.querySelector('body');
parentElement.style.fontSize = '16px'; // Setting the parent font size to 16px

const childElement = document.createElement('p');
childElement.textContent = 'This is some dynamic text';
childElement.style.fontSize = '2em'; // The child element's font size will be 32 pixels (16 * 2)
document.body.appendChild(childElement);

rem Unit

The rem unit is also a relative unit, but it is based on the root font size. In other words, the root font size is the font size of the HTML element, and all other elements inherit this value. By default, the root font size is 16 pixels, so 1 rem equals 16 pixels. However, you can change the root font size to any desired value using CSS:

html {
font-size: 20px; /* Setting the root font size to 20 pixels */
}

With the root font size set to 20 pixels, 1 rem now equals 20 pixels. This means that using rem units allows you to create consistent typography across your entire website, regardless of the parent element's font size.

// Example of using rem units for dynamic text
const rootElement = document.querySelector('html');
rootElement.style.fontSize = '20px'; // Setting the root font size to 20 pixels

const childElement = document.createElement('p');
childElement.textContent = 'This is some dynamic text';
childElement.style.fontSize = '1rem'; // The child element's font size will be 20 pixels (1 * 20)
document.body.appendChild(childElement);

Dynamic Type and Responsive Design

Dynamic type plays a significant role in responsive design by allowing text to adapt to different screen sizes. You can use CSS media queries to adjust the root font size based on the viewport width, ensuring that your website remains readable on various devices.

@media only screen and (min-width: 768px) {
html {
font-size: 18px;
}
}

@media only screen and (min-width: 1024px) {
html {
font-size: 20px;
}
}

Worked Example

Let's create a simple web page that allows users to adjust the text size dynamically using JavaScript and dynamic type units.

  1. Create an HTML file called dynamic_type.html.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dynamic Type Example</title>
<style>
body {
font-size: 16px; /* Default root font size */
}

/* Adding media queries for responsive design */
@media only screen and (min-width: 768px) {
body {
font-size: 18px;
}
}

@media only screen and (min-width: 1024px) {
body {
font-size: 20px;
}
}
</style>
</head>
<body>
<h1>Dynamic Type Example</h1>
<div id="text">This is some dynamic text.</div>
<button onclick="toggleUnits()">Toggle between em and rem units</button>

<script>
let textElement = document.getElementById('text');
let currentUnits = 'em'; // Initialize with em units
let rootFontSize = 16; // Default root font size

function toggleUnits() {
if (currentUnits === 'em') {
rootFontSize = parseFloat(getComputedStyle(document.querySelector('html')).fontSize);
textElement.style.fontSize = `${rootFontSize * 2}px`;
currentUnits = 'rem';
} else {
textElement.style.fontSize = `${rootFontSize}rem`;
currentUnits = 'em';
}
}
</script>
</body>
</html>

In this example, we have a simple web page with a heading, a paragraph of dynamic text, and a button to toggle between em and rem units. The JavaScript code sets the initial font size to 2 em units (32 pixels by default) and provides a function to switch between the two units when clicking the button. Additionally, we've added media queries in the CSS to adjust the root font size for different screen sizes.

Common Mistakes

  1. Forgetting to update the parent element's font size: When using em units, it's essential to set the font size of the parent element before setting the child elements' font sizes. Otherwise, the child elements will inherit the default font size (usually 16 pixels), and adjusting the parent's font size won't affect them.
  1. Not understanding the difference between em and rem units: While both em and rem are relative units, they behave differently based on their relationship to the parent element or root font size. Make sure you understand when to use each unit for optimal results.
  1. Ignoring accessibility considerations: Dynamic type is an excellent tool for improving web accessibility. However, it's essential to ensure that users can easily adjust the text size and that the website works well with different font sizes. Provide clear instructions on how to change the font size and make sure that the website works well with various screen sizes using media queries.
  1. Not considering responsive design: When using dynamic type, it's essential to ensure that your website adapts to different screen sizes. use CSS media queries to adjust the root font size for optimal readability on various devices.
  1. Not testing with assistive technologies: To ensure that your dynamic type implementation is accessible, test your website using assistive technologies like screen readers and keyboard navigation. Make sure that users can easily navigate and adjust the text size using these tools.

Practice Questions

  1. Write a JavaScript function that increases the font size of all ` elements by 20% when a button is clicked using em` units.
function increaseFontSize() {
const paragraphs = document.getElementsByTagName('p');
for (let i = 0; i < paragraphs.length; i++) {
paragraphs[i].style.fontSize = `${parseFloat(paragraphs[i].style.fontSize) * 1.2}em`;
}
}
  1. Modify the previous example to allow users to adjust the font size using a slider input instead of a button.
<!-- Add this code inside the <body> tag -->
<input type="range" id="fontSizeSlider" min="10" max="30" value="16">
<script>
const textElement = document.getElementById('text');
const slider = document.getElementById('fontSizeSlider');

slider.addEventListener('input', function () {
textElement.style.fontSize = `${slider.value}px`;
});
</script>
  1. Create a JavaScript function that adjusts the root font size based on the user's screen width using media queries and rem units.
function adjustRootFontSize() {
const screenWidth = window.innerWidth;
if (screenWidth < 768) {
document.querySelector('html').style.fontSize = '12px';
} else if (screenWidth < 1024) {
document.querySelector('html').style.fontSize = '16px';
} else {
document.querySelector('html').style.fontSize = '20px';
}
}
  1. Write a JavaScript function that adjusts the font size of all ` - elements based on the user's preference using rem` units.
function setPreferredFontSize(preferredFontSize) {
const headings = document.getElementsByTagName('h*');
for (let i = 0; i < headings.length; i++) {
headings[i].style.fontSize = `${preferredFontSize}rem`;
}
}

FAQ

  1. Why should I use dynamic type in my web development projects?

Dynamic type allows you to create a more accessible and user-friendly experience by adjusting the text size based on users' preferences or screen sizes. It is especially important for improving accessibility for visually impaired users who may require larger font sizes to comfortably read web content.

  1. What are the differences between em units and rem units in JavaScript?

em units are based on the font size of the parent element, while rem units are based on the root font size. Using rem units allows you to create consistent typography across your entire website, regardless of the parent element's font size.

  1. How can I ensure that my dynamic type implementation is accessible?

To make your dynamic type implementation more accessible, provide clear instructions on how users can adjust the text size and make sure that the website works well with different font sizes. use media queries to adapt the root font size for various screen sizes and test your website with assistive technologies like screen readers.

  1. What are some best practices for using dynamic type in my web development projects?

Some best practices for using dynamic type include providing clear instructions on how users can adjust the text size, utilizing media queries to adapt the root font size for various screen sizes, and testing your website with assistive technologies like screen readers to ensure accessibility. Additionally, consider using responsive design principles to create a consistent user experience across different devices.

  1. How can I make my dynamic type implementation more efficient?

To make your dynamic type implementation more efficient, store the root font size in a variable and update it only when necessary. This will prevent unnecessary calculations when adjusting the font sizes of child elements. Additionally, consider using CSS custom properties (CSS variables) to store shared values like the root font size, which can improve code maintainability and readability.

  1. What are some common mistakes to avoid when implementing dynamic type?

Common mistakes to avoid include forgetting to update the parent element's font size, not understanding the difference between em and rem units, ignoring accessibility considerations, not considering responsive design, and not testing with assistive technologies. Additionally, be mindful of potential issues like text wrapping and line height adjustments when changing font sizes dynamically.

  1. How can I ensure that my dynamic type implementation is compatible across different browsers?

To ensure compatibility across different browsers, test your dynamic type implementation in multiple browsers and devices. Make sure that the website works as expected and that there are no unexpected issues or discrepancies between browsers. Additionally, consider using polyfills or

Dynamic Type (JavaScript) | JavaScript | XQA Learn