Home > Enterprise >  How to make text in flexbox always fit inside viewport?
How to make text in flexbox always fit inside viewport?

Time:06-02

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?

CodePudding user response:

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>

CodePudding user response:

You shouldn't use vw or vmin units on their own with font-size - it can create accessbility issues, particularly on phones. When a user with sight issues pinches their phone screen to zoom in the font stays the same size.

To have a solution that is accessible you should use clamp() to combine rems (ideally) or similar and have vw as the 'fluid' middle value of the property.

.text-box {
  font-size: clamp(2rem, 6vw, 4rem);
}
  • Related