1

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.

Shaun Dreclin
  • 292
  • 1
  • 3
  • 10
  • Possible duplicate of [How can I count text lines inside an DOM element? Can I?](http://stackoverflow.com/questions/783899/how-can-i-count-text-lines-inside-an-dom-element-can-i) – damos May 20 '16 at 06:29
  • use font size in percentage like label { font-size:60%; } – code.rider May 20 '16 at 06:47

1 Answers1

1

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) {
  divElement.style.fontSize = fontSize + "px"
  fontSize--;
}

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

Parag Bhayani
  • 3,280
  • 2
  • 28
  • 52
  • Yes this is what I needed! I had to add white-space: nowrap; to my div because the extra text was wrapping and scrolling vertically rather than horizontally, but it works great now. Thank you :D – Shaun Dreclin May 20 '16 at 20:54