Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As much as I love the occasional upvotes I get for this answer (thanks!), this is really not the greatest approach to this problem. Please check out some of the other wonderful answers here, especially the ones that have found solutions without looping.</p> <hr> <p>Still, for the sake of reference, here's my <strong>original answer</strong>:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;style type="text/css"&gt; #dynamicDiv { background: #CCCCCC; width: 300px; height: 100px; font-size: 64px; overflow: hidden; } &lt;/style&gt; &lt;script type="text/javascript"&gt; function shrink() { var textSpan = document.getElementById("dynamicSpan"); var textDiv = document.getElementById("dynamicDiv"); textSpan.style.fontSize = 64; while(textSpan.offsetHeight &gt; textDiv.offsetHeight) { textSpan.style.fontSize = parseInt(textSpan.style.fontSize) - 1; } } &lt;/script&gt; &lt;/head&gt; &lt;body onload="shrink()"&gt; &lt;div id="dynamicDiv"&gt;&lt;span id="dynamicSpan"&gt;DYNAMIC FONT&lt;/span&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <hr> <p>And here's a version with <strong>classes</strong>:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;style type="text/css"&gt; .dynamicDiv { background: #CCCCCC; width: 300px; height: 100px; font-size: 64px; overflow: hidden; } &lt;/style&gt; &lt;script type="text/javascript"&gt; function shrink() { var textDivs = document.getElementsByClassName("dynamicDiv"); var textDivsLength = textDivs.length; // Loop through all of the dynamic divs on the page for(var i=0; i&lt;textDivsLength; i++) { var textDiv = textDivs[i]; // Loop through all of the dynamic spans within the div var textSpan = textDiv.getElementsByClassName("dynamicSpan")[0]; // Use the same looping logic as before textSpan.style.fontSize = 64; while(textSpan.offsetHeight &gt; textDiv.offsetHeight) { textSpan.style.fontSize = parseInt(textSpan.style.fontSize) - 1; } } } &lt;/script&gt; &lt;/head&gt; &lt;body onload="shrink()"&gt; &lt;div class="dynamicDiv"&gt;&lt;span class="dynamicSpan"&gt;DYNAMIC FONT&lt;/span&gt;&lt;/div&gt; &lt;div class="dynamicDiv"&gt;&lt;span class="dynamicSpan"&gt;ANOTHER DYNAMIC FONT&lt;/span&gt;&lt;/div&gt; &lt;div class="dynamicDiv"&gt;&lt;span class="dynamicSpan"&gt;AND YET ANOTHER DYNAMIC FONT&lt;/span&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload