0

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>
  • You could use view-port width font-size, like `font-size: 15vw`, this will mean 15% width of the viewport (not the div, unless the div is 100% to the window size). Specifically for your need, you might wanna use canvas like on this question https://stackoverflow.com/questions/39197240/css-vw-and-vh-but-relative-to-the-parent-instead-of-viewport – Damzaky Sep 23 '22 at 03:39
  • https://www.youtube.com/watch?v=KvwR9Ti1p5s&ab_channel=nexTRIE – Gerard Sep 23 '22 at 06:20
  • To do this accurately and automatically for any text and any font you will need to use JavaScript. Is that possible in your case? – A Haworth Sep 23 '22 at 07:31

1 Answers1

-1

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.

schmauch
  • 630
  • 1
  • 7
  • 10