1

I need to fit variable amounts of text into rectangle divs of variable sizes, which are themselves responsive (using vw/vh).

There are hundreds of divs which all have a different size, and I don't know it in advance: it is calculated from original dimensions in centimeters, in order to keep their aspect ratio. Each div has text inside, which should fit to the container (not perfectly, just no overflow). Usually there is a lot of text overflowing, but I can't have a scrollbar, the text should fit the container.

A few things to keep in mind:

  • the divs aspect ratio must be preserved
  • linebreaks of the text must be preserved
  • it does not matter if the text is too small to be legible

So far I've tried to adapt the font-size with viewport units. The problem is that the font-size will be different for each div. I would need some equation to calculate the font size based on the amount of text and/or size of the container.

Here are a few examples: https://codepen.io/gramm/pen/VJPavg

div#tm12901 {
  width: 15.952380952380954vh;
  height: 50vh;
  font-size: 0.8vh;
  line-height: 1.5;
  background: Pink;
}

I've also tried to detect overflow, but so far with no success (it's probably easy to do and I just don't have the js knowledge).

Another example: https://codepen.io/gramm/pen/MMJpdb

//trying to detect overflow
$('.text').each(function(){
  if($(this).clientHeight < $(this).scrollHeight){
    console.log('overflow detected!');
  }
});

Is there a better method: calculate font-size, or detect overflow? And do you have any pointers to help with either method?

For the detect-overflow method, would it be a problem that the divs will change size each time the window is resized?

gramm
  • 41
  • 6
  • 1
    https://stackoverflow.com/questions/16056591/font-scaling-based-on-width-of-container?rq=1 – Paulie_D Jun 20 '19 at 15:36
  • Thanks for the link. I've tried the css tricks https://css-tricks.com/fitting-text-to-a-container/ but I always need some "magic number", and the problem is that the magic number will be different for each case. Plus some of the plugins I've tried, like textfit, don't preserve the linebreaks. – gramm Jun 21 '19 at 09:52
  • PS: here is the example with textfit: https://codepen.io/gramm/pen/zVNNQv (still magic numbers, and I can see that linbreaks are fluctuating when I resize the window). – gramm Jun 21 '19 at 10:00
  • Related to the calculate question: https://stackoverflow.com/a/118251/2690257 – FabricioG Jul 01 '23 at 23:48

0 Answers0