Skip to content

A simple, dependency-free JavaScript utility that dynamically adjusts the font size of text to make it fit perfectly within its parent container's width. This script is ideal for headlines, responsive titles, and any design where text needs to scale precisely with its containing element.

License

Notifications You must be signed in to change notification settings

Icedor/Fit-text-to-container

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Fit Text to Container

A simple, dependency-free JavaScript utility that dynamically adjusts the font size of text to make it fit perfectly within its parent container's width. This script is ideal for headlines, responsive titles, and any design where text needs to scale precisely with its containing element.

Features

  • Fully Dynamic: Adjusts font size based on both the container's width and the length of the text content.
  • Responsive: Automatically re-calculates on browser resize or changes to the container's size (using ResizeObserver).
  • Lightweight: Tiny footprint with no external libraries or dependencies.
  • Easy to Use: Simply add a class to your text elements and initialize the script.

Live Demo

You can see the script in action and experiment with it on CodePen:

Live Demo on CodePen


Usage

Follow these three simple steps to get started:

1. Include the CSS and JS files

Link the style.css and scripts.js files in your HTML. The CSS contains the necessary CSS variable that the script uses to apply the font size.

<link rel="stylesheet" href="style.css">
<script src="scripts.js"></script>

2. Add the Class to Your Text

<div id="my-container">
    <span class="icey_text_fit">This text will fit the container!</span>
</div>

3. Initialize the Script

Initialize the script and set up observers for any containers whose size might change dynamically. Add the following script block before your closing tag.

<script>
    // Wait for the DOM to be fully loaded
    window.addEventListener('DOMContentLoaded', () => {
        // Run the function on initial load
        icey_textFit(); 

        // Create observers to re-run the function on resize events
        const container1 = document.getElementById("my-container");
        if (container1) {
            new ResizeObserver(icey_textFit).observe(container1);
        }
        
        // Re-run on browser window resize
        window.addEventListener("resize", icey_textFit);
    });
</script>

About

A simple, dependency-free JavaScript utility that dynamically adjusts the font size of text to make it fit perfectly within its parent container's width. This script is ideal for headlines, responsive titles, and any design where text needs to scale precisely with its containing element.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published