0

All those duplicates you guys mention only deals with the width of the div. I need to address the height of the div as well. So the content can't go outside of the div height-wise as well. I tried all the similar questions and their answers, none of them contained the text, the text always overflowed height-wise.

Examples of the questions I have tried: 1. Font scaling based on width of container 2. resize font-size according to div size

Now to the question.

I have a div with a fixed height and width. I need the text to reduce the font size as the text content length increases in size so that it beings to overflow. I saw several other questions in here which only deals with the width of the div. Because of this, with those solutions, my text would just overflow vertically.

I really don't care if the solution is by using CSS or javascript. Thanks for the help in advance.

This is the code with which I am trying to get it work:

<div class="box">
  <span>
    This is a really long sentence to demonstrate how it doesn't fit inside the box and doesn't do what I want.
  </span>
</div>

.box {
  margin: 10px;
  width: 200px;
  height: 50px;
  border: 1px solid black;
}

Heres the jsfiddle: https://jsfiddle.net/wnkzy0u8/1/

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
defiant
  • 3,161
  • 11
  • 41
  • 65

1 Answers1

0

You can do this by calculating the right font size using a Javascript function:

const box = document.getElementById('box')
const text = document.getElementById('text');

const boxHeight = parseInt(window.getComputedStyle(box).height);

const getTextHeight = () => parseInt(window.getComputedStyle(text).height);
const getTextFontSize = () => parseInt(window.getComputedStyle(text).fontSize);

while (getTextHeight() > boxHeight) {
  text.style.fontSize = getTextFontSize() - 1 + 'px'
}
.box {
  margin: 10px;
  width: 200px;
  height: 50px;
  border: 1px solid black;
}
<div id="box" class="box">
  <div id="text">
    This is a really long sentence to demonstrate how it doesn't fit inside the box and doesn't do what I want.
  </div>
</div>
giuseppedeponte
  • 2,366
  • 1
  • 9
  • 19