Automatically resize text to fit a fixed div

Viewed 38

I have a div with a fixed size. Is it possible for the font size to adjust automatically to fit the div size? For example, if the text is too long (overflow) the font size will become smaller and vice versa.

  <div
    style="background-color:aqua; overflow:hidden; width:10rem; height:3.5rem; font-size:4rem;"
  >
    Hello World
  </div>
1 Answers

You can adjust the font size depending on content's length to make the text fit a div. You could use JavaScript to get the contnent's lenght. Whit it you can calculate the width.

But be aware that the letters have different widths (www takes more place than iii). You could overcome this by using font-family:monospace.

Here's an example:

var cntnr = document.getElementById('container');
var lngth = cntnr.textContent.length;
var fntsz = 90 / lngth;
cntnr.style.fontSize = fntsz + 'vw';
#container {
  width: 50vw;
  font-family: monospace;
  background-color: #efefef;
  text-align: center;
}
<div id="container">Hello World!</div>

Another drawback is that you loose control over the height. E.g. if there's only a single letter, it will be huge.

Related