dungey_140
dungey_140

Reputation: 2802

Text using VW unit not working

I'm hoping to use VW units to size my typography, but when doing so the text is huge and obviously larger than the viewport width. Essentially I want my text to be responsive within the parent .container, so the text is never cropped or overflowed as it would be if using a static size unit like px or em?

HTML

<div class="container">
    <h1>Responsive Typography!</h1>
</div>

CSS

.container {
  width: 100%;
  background: red;
  height: 100%;
}

h1 {
  font-size: 40vw;
}

FIDDLE

Upvotes: 0

Views: 6857

Answers (1)

Jordan Gray
Jordan Gray

Reputation: 16499

Your Fiddle is rendering correctly.

  • font-size, classically, referred to the width of a capital letter M. Let's go with that for now.*
  • 1vw is 1% of the viewport width.

Thus, font-size: 40vw roughly means "render this text such that the width of a capital letter M would be 40% of the viewport width". In other words, each individual character is going to be pretty huge.

It's not going to break to a new line because it's all one word, and CSS only breaks between words by default. (To break on characters within a word, you would use word-break: break-all on the element. It usually looks terrible, though.)

You confirmed in a comment that you're trying to scale up the font size in your header so that the full text in it is some percentage of the viewport width. Depending on your circumstances, you can either

  1. use a smaller font-size, still in vw, and accept that text won't always be a predictable fixed width; or
  2. try something like FitText to dynamically resize the font.

It's a shame, but there isn't a way to do quite what you want with pure CSS; as is often the case your choices are to compromise on your design goal or use some clever JS/hacks to achieve it.


* A note on font-size: what I said above isn't really how font-size is worked out; it just happens to be close enough for most fonts and it makes my answer easier to read. The actual situation is more complicated.

A more accurate rule-of-thumb is the body height, i.e. the vertical distance from the top of an ascender (upper part of letters like b, d and h) to the bottom of a descender (lower part of letters like g, j and p) on the same line. However, even this is very course and often wrong; it ultimately comes down to the font metrics, and will vary significantly between fonts.

Upvotes: 2

Related Questions