The Book of CSS3 - A Developer\'s Guide to the Future of Web Design (2nd edition)

(C. Jardin) #1
Values and Sizing 201

This code illustrates the problem:


...


Now, imagine that .parent is 75 percent of the viewport width, and you
want .child to be 65 percent of the viewport width—not the width of its
parent. To do this, you have to divide 65 by 75, giving you a result of 86.666
(percent). This calculation is simple enough, but the deeper the nesting
goes, the more complex the calculations become.
A better solution is to use CSS3’s viewport-relative units—vh and vw—
which represent viewport height and width, respectively. Each unit of value
represents 1 percent of the appropriate viewport dimension: 1vh is 1 per-
cent of the viewport height, and 1vw is 1 percent of the viewport width. For
example, the following code makes an element 75 percent of the viewport
width and 50 percent of its height:


E {
height: 50vh;
width: 75vw;
}


The advantage of using these units is that when elements are nested,
the units remain relative to the viewport. So, in the case of my previous
example, to make .child 65 percent of the total viewport width, you simply
do this:


.child { width: 65vw; }


No calculation required!
Another pair of supplemental units is available, too: vmax is equivalent
to whichever is the greater value of vh and vw, and vmin is equivalent to the
lesser value. For instance, if the viewport were 480×640, the height would
be greater, so vmax would be equivalent to vh, and vmin would be equal to vw.
Swap the viewport dimensions (640×480), and vmax and vmin reverse their
values.
So if you presume a viewport of 480×640, in the following code snippet,
element E is 640px wide, and element F is 480px wide:


E { width: 100vmax; }
F { width: 100vmin; }


The utility of vmax and vmin is in ensuring an element remains propor-
tional to the viewport regardless of orientation—useful when that orienta-
tion can easily change, such as on a mobile or tablet device.

Free download pdf