Shaun Dreclin Shaun Dreclin - 1 year ago 88
Javascript Question

Resizing an arbitrary length string to fit into a fixed-size div

Having trouble finding a solution to this. I've got a "button" div 100px wide and 30px tall with a variable label. I want the font size to shrink itself so that the entire label text is always visible.

JS or CSS solutions both work for me, just no jquery.

In flash I solved this problem by checking the number of lines of text, if it's over 1 shrink the font size until it all fits in one line. Not sure if that's possible in javascript.

Edit: Not a duplicate, that person had a variable sized container so different solutions were possible.

Answer Source

One thing here you can do is get the label text into similar size of the div with following CSS attributes and then count it's scrollwidth, then write a javascript loop and decrease font-size by some pixels till you find it's scrollwidth is less than your desired width.

white-space: pre;
overflow-x: scroll;

Small Javascript code which I tried

// dummy divelement
var divElement = document.getElementById('#myelement')
var fontSize = 15; // Starting from 15
while(divElement.offsetWidth < divElement.scrollWidth) { = fontSize + "px"

Does this answer your question? or should I provide you whole example?