What is vh in CSS: Understanding Viewport Height Unit
vh stands for viewport height and represents 1% of the height of the browser window. It is a relative length unit that helps create layouts that adjust automatically to the screen size.How It Works
The vh unit measures the height of the visible area of your browser window, called the viewport. Imagine the browser window as a rectangle; 1 vh equals 1% of that rectangle's height. So if your screen height is 800 pixels, 1 vh equals 8 pixels.
This means if you set an element's height to 50 vh, it will take up half the height of the visible browser window, no matter what device or screen size you use. This makes vh very useful for creating designs that adapt smoothly to different screen sizes, like phones, tablets, or desktops.
Example
This example shows a box that fills half the height of the browser window using vh.
html, body {
margin: 0;
height: 100%;
}
.box {
height: 50vh;
background-color: #4CAF50;
color: white;
display: flex;
justify-content: center;
align-items: center;
font-size: 2rem;
}
When to Use
Use vh when you want elements to size relative to the browser height. For example, full-screen hero sections, vertical centering, or making sure a footer stays at the bottom of the viewport.
It is especially helpful for responsive designs where you want content to fill a portion of the screen regardless of device size. However, be careful on mobile browsers where the viewport height can change when the address bar shows or hides.
Key Points
vhmeans 1% of the viewport height.- It helps create flexible, responsive layouts.
- Works well for full-height sections or vertical sizing.
- May behave differently on mobile browsers due to dynamic toolbars.
Key Takeaways
vh is a CSS unit equal to 1% of the browser window height.