I have a 100vh flex container, direction column.
Below it I have a dynamic number of flex items with the same height. This flex items altogether take all vertical space:
<div>
<ul class="container">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
and css:
ul {
display: flex;
flex-direction: column;
height: 100vh;
}
li {
flex: 1 1 auto;
}
The items contain text. And I want to fit the text to the height of the item. So I use js, with viewport units to calculate the right font size:
var lis = document.querySelectorAll('li');
var fontsize = (100 / lis.length) * 0.8;
document.querySelector('.container').style.fontSize = fontsize + "vh";
Here is the full working fiddle I just described.
My problem is that if a flex item contains text enough that it wraps onto one or more new lines, the approach does not work anymore.
<div>
<ul class="container">
<li>1</li>
<li>2</li>
<li>multiline becomes a problem with this approach</li>
</ul>
</div>
Here is the demonstration of the problem.
To calculate font-size for a multi line item, I need to know how many lines it occupies, but that in itself depends on font-size. So it is a problem that eats its own tail.
My approach
A possible approach I can think of would be the following:
1 Detect number of li's
2 Trigger font-size calculation as seen above and apply
3 Calculate if any lis text will wrap onto new lines and how many (how?)
3.a. If no texts wrap into new lines stop here.
3.b. If there is text that wraps into new lines
3.b.1. Sum number of li's + all new lines on all multiline li's
3.b.2. Re-trigger font-size calculation with this number and apply
3.b.3. Calculate again if any li's text will wrap onto how many new lines, and compare with before font-size change.
3.b.4.a. If there are the same number of new lines, stop here.
3.b.4.b. If there are more new lines, repeat from step 3.b.1
But this approach seems dirty, and can lead to many steps of font size calculation and adjustment. Plus I am not sure how could I perform step 3.
So, how to approach this problem?
This question has been flagged as possible duplicate of this other question. But that question specifically asks for fitting the text into one line, which is a very different matter.
That said I could be taking some hints out of some of the answers, as they attempt to guess if a text overflows a div. In particular I am curious about this answer as @Hoffmann specifically says to attempt to avoid the loop problem I mention in my approach. I'll attempt to understand the code of his plugin, now maintained by someone else here: https://github.com/BrOrlandi/big-text.js/blob/master/big-text.js
Thank you