I’ve recently fallen in love with the CSS3 vh
property. (vh
stands for “viewport-height.”) It lets you make things a certain percentage of the height of your browser window itself—whether that “viewport” is a tablet screen, a phone screen (in portrait or landscape), a laptop, a desktop, a smart fridge(?), or what have you.
In this text and video Quick Guide, we’ll demo a use of the vh
unit and show you the code behind it.
How to Use CSS3’s vh
Unit: Video Demo
Here’s a video tutorial diving into vh
:
What vh
is Good For
Want a demo? Here’s an image that is 90% as tall as your browser—meaning you can always see the whole thing without scrolling!
How to Use the CSS vh
(viewport-height) Unit: Code Demo
Here’s the complete code for the image above:
<div style="background: url('https://c1.staticflickr.com/4/3947/15652141152_3317e03054_k.jpg'); background-size: cover; background-position: 50% 50%; height: 90vh;" /></div>
The most important thing to note is simply the height: 90vh;
on the div
itself. That’s what tells the div
to be just slightly less tall than your browser is.
There are also some background-image
shenanigans to make sure that the image, which is landscape-oriented, clips rather than distorting in this potentially-very-lipstick-tube-shaped post content. That’s a detail, though—the cool stuff is simply setting element sizes with vh
.
Where I Think the vh
Unit is Useful in Web Development
This feels like the height: 100%;
CSS element that should’ve worked the whole time—although, sadly, it only works relative to the browser. (For more options that are relative to a containing element, have a look at Flexbox.)
I can see this being huge (if it isn’t already—the property’s not new, just new to me) for people developing single-page layouts with a full-page hero image and multiple full-page sections, preferably without dipping into the Big Bag of Ugly and Fragile jQuery Hacks. I can also see it being really big for very simple and device-dependent mobile app layouts, whether “app-like” but browser-based or actually native with a tool like React Native.
Thanks for reading!