Viewport-Based CSS Measurements
Let’s kick the series off with a quick one.
Fast-forward to 2010, CSS3 came along and it introduced a lot of new features including viewport-based measurement units. That’s what we’re looking at today.
vw: represents 1% of the viewport’s width
vh: represents 1% of the viewport’s height
One important thing to remember is that these units will ALWAYS be relative to the viewport. The only exception here is if you’re using it inside an iframe (since they are sort of separate windows on their own).
Let’s See it in Action
In this first example, we’ll try to create our own pop-up modal. The goal is to make it so that the modal’s width is always 80% of the viewport’s width, its height always 60% of the viewport’s height, and always at the center of the page.
The use of
vh above were pretty straight-forward. But some of you might be saying “But I can also achieve this using
%, why use
Let’s look at another example. Suppose we’re creating a site/app similar to the Clear app, and we want it to always be able to accommodate 4 items in the screen, and clicking on an item will make it expand to cover the whole viewport. How do we do it?
How easy was that? Using
vh, we were able to meet all the requirements without lengthy
Combining it with calc()
You can also achieve great results by combining these units with the CSS
calc function. It can look something like this:
width: calc(100vw - 80px);
margin: 0 auto;
This will force the
.modal-body to always be
80px less than the viewport’s width (hence giving it a
40px horizontal space on both sides), but ensure that it’ll never go pass
There’s still a lot you can do with these, but I’ll leave it up to your creativity and imagination. I hope this helped!
- IE 10+
- Firefox 19+
- Chrome 34+
- Safari 7+
- Android 4.4+
- iOS 6+
For more info, you can read the full documentation in Can I Use.