1. The script
function fontFitWidth(el, settings = {}) { el.style.whiteSpace = "nowrap" el.style.fontSize = (settings.min | 9) + "px"; fontSize = (settings.min | 9); while(el.scrollWidth <= el.offsetWidth && fontSize < (settings.max | Infinity)) { fontSize++; el.style.fontSize = fontSize + "px"; } fontSize--; el.style.fontSize = fontSize + "px"; }
2. How to call this function? Example.
HTML:
<div id="title" style="width: 100px; font-size: 50px;">Some large input text</div>
JS:
fontFitWidth(document.querySelector("#title"), {max: 159, min: 11});
3. Available settings options
max
- the maximum font size value (in px);
min
- the minimum font size value (in px).
If you need a reliable Dedicated Server or VPS, you should definitely try InterServer Hosting. You can test InterServer for 1 Penny, for the first month, using this coupon code: WSG1PENNY.