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.
- 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.
You can see the script in action and experiment with it on CodePen:
Follow these three simple steps to get started:
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>
<div id="my-container">
<span class="icey_text_fit">This text will fit the container!</span>
</div>
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>