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?