vh stands for “viewport height.” It represents 1% of the viewport’s height, which is the height of the browser window. This makes vh units responsive, automatically adjusting their size based on the screen’s height.
Using vh Units
Set Element Dimensions
- To set the height or width of an element using
vh, simply specify the desired percentage value followed byvh. - For example, to make an element 50% of the viewport’s height, you would use:
height: 50vh;
Create Responsive Layouts
vhunits are ideal for creating responsive layouts where elements scale proportionally with the screen size.- For instance, to create a full-height container that expands to the entire viewport, you could use:
.container {
height: 100vh;
}
Combine with Other Units
- You can combine
vhunits with other CSS units likepx,em, orremfor more precise control. - For example, to set a minimum height of 200 pixels but allow the element to grow up to 50% of the viewport height, you could use:
min-height: 200px;
max-height: 50vh;
Key Points
vhunits are relative to the viewport’s height, making them responsive by nature.- They are useful for creating dynamic layouts that adapt to different screen sizes.
- Combining
vhwith other units provides flexibility in controlling element dimensions.
Example
<!DOCTYPE html>
<html>
<head>
<title>Using vh Units</title>
<style>
.container {
height: 100vh;
background-color: lightblue;
display: flex;
justify-content: center;
align-items: center;
}
.content {
background-color: white;
padding: 20px;
width: 80vh;
}
</style>
</head>
<body>
<div class="container">
<div class="content">
This content will scale with the viewport height.
</div>
</div>
</body>
</html>
In this example, the .container element occupies the entire viewport height, and the .content element’s width is set to 80% of the viewport height, ensuring it scales proportionally with the screen size.