With the popularity of CSS3, everyone must be familiar with Viewport, especially on mobile devices. Today, I want to introduce a type of Viewport unit that may seem inconspicuous but is absolutely delightful to use. They are vw
, vh
, vmin
, and vmax
.
With so many new kids on the block in the front-end world, what is this guy doing? Why should I learn it?
Let’s keep you in suspense and first take a look at the Demo.
If you look closely, there are a few points here worth discussing:
First, the font size:
Observant readers should notice that the font size changes with the window width; when the window width is small, the font size is also small, and vice versa. Normally, achieving this effect with CSS is not so easy.
Second, the height:
The height of the grey box is always consistent with the screen height. In traditional CSS, we would write:
html,body {
height: 100%;
}
.box {
height: 100%
}
Of the first three lines, we need to specify the height of html
and body
. Why do we do this? Because the height of the DOM is calculated based on the parent node. If we do not specify the height of the parent node, the child node cannot achieve a height of 100% either.
Notice that the line height of the text also remains consistent with the height of the window.
After seeing the Demo above, you must be curious about how it was achieved. Can you guess how many lines of code are needed?
20 lines? 10 lines? 5 lines?
No! The core code actually only needs 3 lines!! Surprised, right? Haha, let’s take a look at what was actually written:
html, body{
margin: 0;
padding: 0;
}
.title {
/*Important 3 lines of code*/
font-size: 5vw;
height: 100vh;
line-height: 100vh;
/********/
text-align: center;
background: grey;
}
Other than the important three lines for .title, the rest is just for aesthetic purposes and can be omitted. Thus, just 3 lines of code are enough to achieve the effect above. Isn't that amazing?
The reason we can solve this with 3 lines of code is mainly thanks to these few units: vw
, vh
, vmax
, and vmin
. So what exactly do they do? The formulas below should clarify:
Actually, these are just 4 simple formulas. At this point, those of you who are not good at English might be mumbling, “Oh no, another four strange words, how am I supposed to remember them?” If you look closely, you will find that these units are just two words combined: where v = viewport, w = width, h = height, therefore, width is viewport + width = vw, and maximum width is viewport + max = vmax. Just remember that their unit is 1%, and you’re set.
As for compatibility, it is as follows:
For specific cases, you can visit Can I Use.
It can be seen that, apart from the Microsoft family, other browsers are quite friendly. When using it, consider graceful degradation, which should not be a big problem.
For example:
font-size: 18px;
font-size: 4vw;
Okay, that’s all for now. Feel free to leave me a message if you have any questions.