As page layouts become more complex, developers require access to a greater range of measurements to bring their designs to life. Beyond the standard percentage widths, r/ems
and pixels we’re used to, the new vw
and vh
measurements (and their related brethren, vmin
and vmax
) provide more powerful ways of describing adaptive designs that can often eliminate reams of @media
breakpoint interventions.
Getting Beyond Percentages
Traditional CSS measurement systems create a few problems in web design:
- Percentage measurements don’t always work as expected. Developers always have to keep margins in mind when sizing elements. Trying to use
% height
on the body doesn’t work as designers think it should.font-size: 50%
makes text half its normal size, rather than creating a dynamic relationship between the text and its container element. - It’s almost impossible to keep shapes perfect. Keeping an element perfectly square and responsive at the same time is very difficult.
vw
and vh
go a fair way towards addressing all of these issues.
Keeping Perfect Rhythm
It’s very easy to make “perfect” shapes on web pages using vw
and vh
. To do so, you have to appreciate that vw
and vh
can be used in almost any CSS property that can take a length measurement. Therefore, if you want an element that is always 20% of the screen width and remains square no matter what the window size, you can apply the same vw
value to both its width
and height
:
div.twentysquare {
background: #999;
width: 20vw;
height: 20vw;
}
(Try resizing the browser window to see the effect on the square).
Using the same method, it would be easy to make a rectangle always be twice as high as it was wide, while scaling to the size of the browser window:
div.onetworect {
width: 20vw; height: 40vw;
}
Sizing a banner to a “perfect” ratio in CSS would be as simple as:
div.goldenrect {
width: 100vw;
height: 61.8vw;
background: red;
}
Fitting "clamped" text inside a responsive box, always perfectly filling the space allotted to it with breaking into new lines would just be a matter of sizing the font in vw
units.
Photograph by Helga Weber, licensed under Creative Commons.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.