Responsive font size with viewport units

Responsive font size with viewport units

Web Designers or Developer always dreamed for a perfect design that looked great no matter what screen size and resolution it was viewed on. But what about those fonts? That great SEO headline looks perfect on a screen of 1600px display, but at 1400px or even at 1200px it breaks lines. Well, that just leaves a bad taste in your mouth, too bad there wasn’t an easy way to take on that. Oh wait, there is…by using “Viewport units” which are designed for the challenges. Previously, we hacked these challenges using percentages as mentioned earlier, or JavaScript. Viewport units, such as vw and vh, set the font-size of an element relative to the dimensions of the viewport:

  • 1vw = 1% of viewport width
  • 1vh = 1% of viewport height

So if we take the following example:

.element {
  font-size: 100vh;
}

Then this will state that the font-size of the element should always be 100% of the height of the viewport at all times (50vh would be 50%, 15vh would be 15% and so on). This new set of units consists of four different units. Two for each axis, and a minimum and maximum value of the two.

  • vw: Relative to 1% of the width of the viewport
  • vh: Relative to 1% of the height of the viewport
  • vmin: Relative to 1% of viewport’s* smaller dimension
  • vmax: Relative to 1% of viewport’s* larger dimension

example: If the viewport is 50cm wide, 1vw = 0.5cm. Just to clarify: 1vmax equals 1vh in portrait mode, whilst in landscape mode, 1vmax will equal 1vw. Note: IE9 uses vm instead of vmin. It does not support vmax.

Browser Support

IE 10+, Firefox 19+, Chrome 34+, Safari 7+, Android 4.4+, iOS 6+Supported Chrome 20-34, Safari 6Supported but has repaint issue There are a couple of other specific cross-browser weirdnesses with them, documented on Can I Use.

Not just font-size

For the record, these are just units. Just like em, px, whatever. You can use them on anything, not just font-size. example below will allow allow us to scale up font sizes for responsive devices simply by writing.

@media (max-width:768px){
  body h1 { font-size: 6.3vw;  line-height: 7vw; }
  body h2 { font-size: 6vw; line-height: 7.9vw; }
  body h3 { font-size: 5.7vw; line-height: 7.9vw; }
  body p, body li, body a {  font-size: 0.95vw; }
}

Native usage

If the used unit is not supported, you can easily provide that classic CSS fallback too, like so:

h1 {
  font-size: 36px; /* If vw is supported, font-size is overwritten. If not, UA will use 5em */
  font-size: 5.4vw;  
}

Download an excellent example

About This Author

My name is Parameshwar Roy (P. Roy), and I am a web developer. This is my personal blog to record my own thoughts. Though I am not a natural writer, I love to share my experiences. Hope my experiences will be useful to you…read more about me

Leave A Reply