HomeWeb WorldCSS3Understanding CSS Viewport Units for Responsive Design

Understanding CSS Viewport Units for Responsive Design

Image Courtesy: Hongkiat.com

Responsive, yes that’s word that everyone is talking about in this Web World, no matter whether they are designers or developers.

For making a wonderful responsive web design, there is one thing that can help developers achieve their target, i.e., Viewport-percentage lengths or Viewport Units as they are more frequently referred to. They are the responsive CSS units that allow us to define dimensions as a percentage of the width or the length of the viewport.

W3C defines viewport as “size of the initial containing block”. In other words, a viewport is an area contained within the browser window or any other viewing area on a screen.

Viewport height (vh) & Viewport width (vw)

The vh and vw units stands for the height and width of the actual viewport. The values of these units is a range between 0 to 100.

For example

100vw = 100% of viewport width
100vh = 100% of viewport height

Similarly, if you want your block to take only 10% of the viewport width, then all you have to do is specify the following in the CSS for your HTML block

width: 10vw;

Well, you all must be wondering that what is the major difference between Viewport Units and Percentage Units? The difference between these two is that the Percentage Units inherit the size of their parent element while Viewport Units don’t and are always calculated as the percentage of the viewport size.

!TIP: Scrollbars are also a part of the Viewport size, so if you are gonna use width: 100vw then are gonna see the horizontal scrollbar at the bottom of the browser window. To avoid this, scenario, it's suggested to use width: 100% as this works perfectly fine for responsive designing.

Here is the reference to another great article that lists a handful of real-life examples (with Codepen demos).

You can’t only use viewport units on the width and height properties but on any other one. For instance, you can set the size of paddings and margins using the vw and vh units, too.


Most Popular