Siddharth Thevaril Siddharth Thevaril - 26 days ago 12
CSS Question

Avoid word break while using vw for font size

Does there exist a mathematical relation between the font-size and the screen width so that there is no word break during resize of the width of the viewport/window?

For example, if I set the font size of a paragraph to

16px
, where the first line of the paragraph reads-


Lorem ipsum dolor sit amet, consectetur adipisicing elit.


If I were to resize the width of my viewport, there would be a word break in case if the viewport width is small to accommodate the sentence because the font-size is set in
px
units.

Now since the font-size increases/decreases during resize of width of viewport if the unit is set in
vw
, I want to make sure there is no word break, imagine you're resizing an image with text on it. Is this possible to achieve?

Answer

You can set your container to a specific vw width, and then set your font-size to a specific vw value. With those two things, resizes should work as you expect, provided the font is loaded explicitly, rather than relying on "whatever font the browser decides to use", so no CSS serif, but also no CSS "Times New Roman" because you don't know which version of that font will end up actually getting used, and so you cannot trust that the font metrics are what you need them to be. So:

  1. load a specific font through an @font-face rule
  2. make sure your container is set to have a width expressed in vw
  3. make sure your container specifies its font-size in vw units.

CSS:

.rs {
  width: 50vw;
  background: lightgreen;
  font-family: lato;
  font-size: 3.3vw;
}

HTML:

....
<link href="https://fonts.googleapis.com/css?family=Lato" 
<div class="rs">
  This is text This is text This is text T
</div>

Live example: http://jsbin.com/januxevebe/edit?html,css,output