The viewport is the visible area of a page in the browser. CSS provides us with units that relate to its size. They are known as the viewport-percentage lengths units. They are vh
, vw
, vmax
and vmin
. These units let us size things relative to the viewport of the user.
vh
& vw
unitsIn CSS, vh
stands for viewport height and vw
for viewport width. As you can see, the first unit is based on the viewport height, and 1vh
is equivalent to 1%
of the viewport height. vw
works the same, but for viewport width. So, 1vw
equals 1%
of the viewport width.
Given a box, we set the width to 20vw and the height to 20vh. Considering the different viewport scenarios listed below, what is the final pixel (px) size for the width and height?
1200px
and 1000px
.In this scenario, the value of
20vw
will be240px
and that of20vh
will be200px
.
1000px
and 1200px
.Here, we can see that the device is rotated. So,
20vw
is now equal to200px
and20vh
equals240px
.
1000px
and 800px
.Notice how the initial viewport is resized.
20vw
=100px
and20vh
=160px
.
vmin
unitsIn CSS, vmin
stands for viewport minimum. The vmin
function is used to set the size of an element as a percentage of the minimum value between the viewport width or height. For example, if the viewport is 1000px
wide and 800px
high, if we set the width of an element to 30vmin
, it will be 30%
of the height. So 30%
of 800px
is 240px
.
vmax
unitsIn CSS, vmax
stands for viewport maximum. The vmax
function ranks elements as a percentage of the maximum value between the viewport width or height. For example, as shown above, an element of 30vmax
would be 30%
of the width, or 300px
.
We use these viewport units in situations where we need to set the element size relative to the viewport. For this practical exercise, let’s create a section that occupies the exact height of the viewport.
First, the markup.
<section class="cover"><h1>Welcome to Educative, Inc.</h1></section>
Next, the style.
body {font-family: 'Lato';}.cover {width: 100%;height: 100vh;color: #fff;background: linear-gradient(115deg, #4e54c8, #8f94fb);display: flex;align-items: center;justify-content: center;}
Note: You’ll notice that for the width, I use
100%
instead of100vw
to make the section take up the full width of the page. This is because thevw
part is used outside the HTML and body elements. But if you still want to usevw
, you can useoverflow-x: hidden
on thebody
element.
Let's put it all together to enjoy the output.
We've looked at viewpoint units in more detail. They are vh
, vw
, vmin
and vmax
. The most commonly used of these are:
vh
, which determines its size based on the viewpoint's height.vw
, whose size is based on the viewpoint’s width.In this shot, we’ve learned that when you want an element to span the full width of the page, it’s best to use percent units instead of viewpoints.