How to make text in flexbox always fit inside viewport?

Issue

I would like to have some text fill the entire browser window but not go beyond the window, i.e. i want all the text to be visible and would like the font size to adjust dynamically to account for this.

The closest I have been able to accomplish is with a flexbox, using this CSS:

.textBox{
    display: flex;
    color: white; 
    background-color: blue;
    font-size: 10vw;
    position: absolute;
    top:0;
    width:100vw;
    height:100vh
}

and this HTML:

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="styles/styles-wearer.css">
    </head>
    <body>
            <div class='textBox'>
              some cool text that is a whole bunch of cool text.  we love great text.  all the text in the world and i have a great time getting text to be in this place.  it is not enough but at least we have some text.
            </div>       
    </body>
</html>

This works well for small windows, e.g. if I have the window size reduced by having the Javascript console open in Chrome. But as the window size grows, the text eventually grows so large that it is cut off and some of it is no longer visible.

Is there a way to make sure that as the flexbox changes size, the font size adjusts to make sure that all the text stays onscreen? Or am I incorrectly setting the size of the flexbox and it’s actually ending up larger than the browser window?

Solution

Try using vmin as a font size unit and clamp the font size for accessibility

.textBox{
  background-color: blue;
  color: white;
  font-size: clamp(1rem, 10vmin, 6rem);
  padding: 2rem;

  position: absolute;
  inset: 0;

  display: flex;
  align-items: center;
}
<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="styles/styles-wearer.css">
    </head>
    <body>
            <div class='textBox'>
              some cool text that is a whole bunch of cool text.  we love great text.  all the text in the world and i have a great time getting text to be in this place.  it is not enough but at least we have some text.
            </div>       
    </body>
</html>

Answered By – Simp4Code

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.