Powercoder
Powercoder

Reputation: 755

CSS - make font be as large as possible to fill container

I have a grid that filled screen and each it's cell contain some text as labels. What should I write in CSS to resize this text to fill container without overflow? Keep in mind it may be restricted by height or by width.

Now it is just

label {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 150pt; /*must be adaptive*/
}

Jsfiddles: grid 3x3, grid 1x10

Or if there is no ideas...
At the moment I have two formulas as alternate variant that can calculate desired font-size relative to height (first) and width (second). I would use min() of them if it was supported. So if there is no elegant solution on CSS, the other question: will it be effectively to define CSS variable and set to it min of formulas with js in window.onresize?

Upvotes: 1

Views: 2495

Answers (2)

Chad H
Chad H

Reputation: 594

I'm pretty sure there's no "pure css" way to accomplish this.

I wrote a js script that checks the container for overflow/scroll-height. Either you start at something small, say 1px font size, and continually increase it until the container has overflow, then shrink it back down 1 notch.

Alternatively, have a really large font size, say 200px (or whatever your MAX is). And do the reverse until there's no longer overflow/scrolling on the container.

You could optimize this by jumping "half way" each time, instead of 1px at a time. So...

200px ? scrollHeight > height || scrollWidth > width : true
100px ? scrollHeight > height || scrollWidth > width : false
150px ? scrollHeight > height || scrollWidth > width : true
125px ? scrollHeight > height || scrollWidth > width : true
... etc etc.

A couple other points:

  • Check scrollHeight AND scrollWidth (a long word that doesn't wrap)
  • hide the container while it's calculating to prevent flicker
  • test, test test, lots of potential issues with this, but I've found it works quite well
  • There's probably a library, just use that if you're lazy ;)

Upvotes: 1

Spammer McSpamface
Spammer McSpamface

Reputation: 1

Try this. It would scale the fonts to each container

            label {
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 150pt;
            font-size: 9vw;
            }

Upvotes: 0

Related Questions