VOOZH about

URL: https://www.geeksforgeeks.org/css/explain-the-concept-of-the-vh-and-vw-units-in-css/

⇱ Explain the concept of the 'vh' and 'vw' units in CSS - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Explain the concept of the 'vh' and 'vw' units in CSS

Last Updated : 18 Jun, 2024

The vh (viewport height) and vw (viewport width) units in CSS are relative length units representing a percentage of the viewport dimensions. These units enable responsive design by sizing elements based on the user's viewport.

Viewport Height ('vh') Unit

The vh unit in CSS stands for viewport height, representing 1% of the viewport's total height. It's used for responsive design, dynamically scaling elements based on the user's viewport height.

vh is commonly used for creating responsive designs where elements scale with the height of the viewport. This unit helps maintain consistent vertical spacing relative to the viewport height.

Syntax

height: 50vh;

Example : Using vh for Responsive Height

In this example we sets .responsive-height to occupy 50% of the viewport height (50vh), styled with a light blue background.

Output:

👁 vh
vh example output


Viewport Width ('vw') Unit

The vw unit in CSS stands for viewport width, representing 1% of the viewport's total width. It's used for responsive design, scaling elements dynamically based on the width of the user's viewport.

vw Frequently used for responsive designs where elements scale with the width of the viewport. It ensures adaptability and optimal layout presentation on diverse screen sizes. This unit helps maintain consistent horizontal spacing relative to the viewport width.

Syntax

width: 50vw;

Example : Using vw for Responsive Width

In this example we sets .responsive-width to occupy 50% of the viewport width (50vw), styled with a light green background.

Output:

👁 vw
vw example output

Differences between vh and vw units in CSS

AspectViewport Height (vh)Viewport Width (vw)
DefinitionRepresents 1% of the viewport's heightRepresents 1% of the viewport's width
UsageUsed for vertical scaling of elementsUsed for horizontal scaling of elements
Common ApplicationsSetting heights, vertical margins, and paddingsSetting widths, horizontal margins, and paddings
Responsive DesignEnsures elements adjust to changes in viewport heightEnsures elements adjust to changes in viewport width
Examplesheight: 50vh; sets height to 50% of viewport heightwidth: 50vw; sets width to 50% of viewport width

Conclusion

Using vh and vw units in CSS allows for responsive and flexible designs that adapt to different viewport sizes. These units are essential for creating layouts that maintain consistent spacing and proportions across various devices and screen sizes.

Comment
Article Tags: