Yurii K
3 min readNov 21, 2023

--

Perfect Fit Every Time: Dynamic Text Resizing for Container Elements with Vanilla JS.

Responsive design is a cornerstone of modern web development. While front-end developers have myriad tools at their disposal for creating responsive layouts, achieving responsive text sizing remains a challenge. Common approaches like using viewport units or media queries only partially solve the issue. So, how can we create truly responsive text sizes?

Requirements for the Solution:

Framework-agnostic: The solution should work across various projects, regardless of whether they use frameworks like Angular or React. We’ll focus on pure JavaScript.

Container Compliance: Text must always fit its container, eliminating the need for media queries for text size adjustments.

Flexibility: The solution should accommodate both single-line and multi-line text configurations.

Setting Up the Test Environment:

I’ll start by creating several containers dynamically with varying text lengths. For this demonstration, I’ll implement some basic settings to control the text, width, and height of each container. Containers with odd indices will display multi-line text in black, while those with even indices will show single-line text in white. I’ll generate text using truncated lorem ipsum strings.

Initial Code Setup
UI

The ‘Apply’ button assigns new width, height, and text values to the containers.

Functionality of the ‘Apply’ Button

Addressing Text Overflow:

What happens when text overflows its container? Typically, we see a scrollbar, indicating that our font size needs adjustment. By comparing the container’s actual dimensions with its scrollable dimensions, we can find an appropriate font size that prevents overflow.

Handling Fluid Container Dimensions:

This approach works well for containers with fixed dimensions. But what about containers without fixed dimensions? One strategy is to create a copy of the container with fixed dimensions, calculate the appropriate font size, and then apply this font size to the original container.

Listening to Window Resize Events:

Finally, we need to adjust the font size dynamically in response to window resize events, ensuring our text remains responsive.

Conclusion:

Responsive text sizing enhances user experience and is crucial for modern web design. By using vanilla JavaScript, we can create a versatile solution that adapts text size to its container, ensuring readability and aesthetic appeal across diverse layouts.

If you need to take a close look at the project here is the link.

--

--

Yurii K

Full-stack developer. In my work, I use Angular and C#. In my free time I write articles for my blog.