min-height and vh units in CSS
min-height and vh units in CSS

In CSS, we often use the height property to set the height of an element. However, sometimes we want the element’s height to automatically adjust to its content, but we don’t want it to be too small. This is where the min-height property comes in handy.
What is min-height
min-height is a CSS property used to set the minimum height of an element. Its purpose is to ensure that the element’s height does not fall below the specified value, even if there is little content.
Use min-height
div {
min-height: 200px;
}
In the example above, we set the min-height of a div element to 200px. This means that no matter how much content is inside the div element, its height will never be less than 200px. This ensures that the element’s height is never too small, making the page look more aesthetically pleasing.
vh Unit
In mobile development, we often encounter inconsistent screen heights. To address this, CSS introduced the vh unit. The vh unit represents the height relative to the viewport; 1vh is equal to 1% of the viewport’s height.
Using the vh Unit
div {
min-height: 50vh;
}
In the example above, we set the min-height of a div element to 50vh. This means that the div element’s minimum height is 50% of the viewport’s height. This means that the div element will occupy half the screen height regardless of the screen size.
Code Example
Let’s look at a simple example that combines the min-height and vh units to set an element’s minimum height.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>min-height and vh</title>
<style>
body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
}
header {
background-color: #333;
color: #fff;
text-align: center;
padding: 10px 0;
min-height: 10vh;
}
main {
background-color: #f4f4f4;
text-align: center;
padding: 20px;
min-height: 80vh;
}
footer {
background-color: #333;
color: #fff;
text-align: center;
padding: 10px 0;
min-height: 10vh;
}
</style>
</head>
<body>
<header>
<h1>Header</h1>
</header>
<main>
<h2>Main Content</h2>
</main>
<footer>
<p>Footer</p>
</footer>
</body>
</html>
In this example, we use the min-height and vh units to set the height of the header, main, and footer elements to ensure they adapt to different screen sizes. When you view this page on different devices, you’ll notice that the heights of the header, main, and footer elements all remain within an appropriate range, making the page look more aesthetically pleasing.
Summary
By using the min-height property and the vh unit, we can better control the height of elements and ensure the page looks its best on different devices. In mobile development, these two properties can help us address inconsistent screen heights and adapt our pages to different screen sizes.