In web design, it is very important to use units of measurement that are appropriate for screen sizes to ensure a responsive and user-friendly experience. In CSS, units such as vh and vw help to achieve a consistent look across different devices by adjusting for the dimensions of the screen. In this guide, we'll cover these units of measurement and their derivatives, dvh, lvh, and svh, and show you how and when to use them.
What are vh and vw?
- vh (viewport height): This unit corresponds to 1% of the height of the screen.
100vh
is equal to the entire screen. When used to set an element to cover the entire screen, the height changes depending on the screen size.
Example: If you want a div element to occupy the full height across the screen:
.full-height { height: 100vh; }
- vw (viewport width): This unit is equal to 1% of the width of the screen. So, 100vw covers the entire screen. This is often used to set an element to the full width of the screen.
.full-width { width: 100vw; }
New vh Derivatives: dvh, lvh, svh
In mobile browsers (especially on smartphones), the screen height can change dynamically because the screen size is different when the browser UI (e.g. the address bar) is visible or hidden. To better manage such variables, new vh derivatives are being used:
- dvh (dynamic viewport height): A unit that adapts to dynamic changes in the browser (such as the address bar opening and closing). It depends on the current effective height of the screen.
- lvh (large viewport height): Represents the screen height when the browser interface elements occupy the least amount of space. This is usually useful when the browser is in full screen mode or when the user interface is hidden.
- svh (small viewport height): Represents the screen height when the browser takes up the most space, i.e. when the user interface is visible. Usually refers to the smallest display height in the browser.
A Real Life Example Problem and Solution
Let's say you need to place a full-screen image on a web page. But when the user scrolls, you notice that the browser address bar goes up and the viewport changes. If you just use classic vh, the height of the image during these transitions may not be what you expect and you may get interruptions. In this case, you can use dvh so that it adapts more appropriately to the dynamic height of the screen:
.fullscreen-image { height: 100dvh; }
In this way, dynamic changes in the browser are immediately reflected in the size of the image, providing a better user experience.