VW in CSS stands for Viewport Width. It’s a relative unit of measurement used to define sizes and layouts on web pages.
How it works:
- 1vw equals 1% of the viewport’s width.
- The viewport is the visible area of the browser window.
.element {
width: 20vw;
height: 15vw;
}
- An element with a width of
20vwwill occupy 20% of the viewport’s width. - A height of
15vwwill be 15% of the viewport’s width.
Why use VW?
- Responsive design: VW units are ideal for creating layouts that adapt to different screen sizes.
- Dynamic sizing: Elements will automatically resize based on the viewport’s width.
Important note:
- While VW is useful for responsive design, it’s essential to consider other units like
vh(viewport height),vmin(minimum of viewport width and height), andvmax(maximum of viewport width and height) for more complex layouts.
Example 1: Full-Width Hero Image
.hero-image {
width: 100vw;
height: 50vh; /* Or any desired height */
object-fit: cover;
}
- The image will always span the entire width of the viewport.
- The height is set to 50% of the viewport height.
object-fit: coverensures the image scales to fit the container while maintaining aspect ratio.
Example 2: Fluid Typography
h1 {
font-size: 3vw;
}
- The heading size will scale proportionally with the viewport width
- This creates a more comfortable reading experience on different screen sizes.