The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Resizing font based on container width using vanilla JS and while Loop

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
  • #275773

    Hi there,

    I am trying to write some logic which will dynamically resize text to fit inside a div container.

    I thought it might be a logically idea to use a while loop to do the text resize so that it can keep reducing the text size until it does not exceed the container width anymore.

    Unfortunately what i have keeps crashing the browser meaning the loop is infinite and not breaking out.

    Heres what I have so far:

    This sedfdg d f dfgdfg dfdfg fdg fdg dfg dfg dfgd fkjfkjdfngkjdfndf kgdfjklg kldfgkjd flkjg dgfjkkbtybrtyrbtybrty jldfjkllk gd jlg djgdjlg jfdggk jndfjng

    var textContent = document.getElementById('headline-2');
    var textContainer = document.getElementById('headline-2-container');    
    var containerwidth = textContainer.clientWidth;
    var containerHeight = textContainer.clientHeight;
    var contentWidth = textContent.offsetWidth;
    var contentHeight = textContent.offsetHeight;
    var fontSize = parseInt(window.getComputedStyle(textContent, null).getPropertyValue("font-size"));
    console.log("Font-size", fontSize);
    console.log("Container height", containerHeight);
    console.log("Content height", contentHeight);
    while (contentHeight > containerHeight) {
      fontSize = 1; = "red"; = fontSize -= 0.5;

    I just put the fontSize = 1 inside the while loop for testing purposes.

    Can anyone work out why the while loop is infinite in this instance?

    Any guidance would be appreciated.

    heres the CodePen link if it makes it easier:



    I think you’d need to update contentHeight inside the loop, it currently stays at the value that was originally set (and if that is beyond the container height, it will loop infinitely).

    Not that I would take this approach though, I would likely go with a single scale transform myself.

Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.