Min-height is a CSS property that is used to set the minimum height of an element. It is similar to the height property, but with one key difference: if the content inside the element is larger than the specified height, the element will expand to fit the content. This makes it a useful property for creating flexible layouts that can adapt to different amounts of content.
The syntax for using min-height is simple:
selector {
min-height: value;
}
Here, the selector can be any valid CSS selector, such as a class, ID, or element selector. The value can be any valid CSS length unit, such as pixels, ems, or percentages.
Let's take a look at some examples to see how min-height works in practice.
In this example, we'll set a fixed min-height of 200 pixels on a div element:
<div class="box">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed euismod, velit eget bibendum bibendum, velit elit bibendum elit, vel bibendum elit elit vel elit.</p>
</div>
.box {
min-height: 200px;
border: 1px solid black;
}
In this example, the div element will have a minimum height of 200 pixels. If the content inside the div is less than 200 pixels, the div will still be 200 pixels tall. If the content is more than 200 pixels, the div will expand to fit the content.
In this example, we'll set a min-height of 50% on a div element:
<div class="box">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed euismod, velit eget bibendum bibendum, velit elit bibendum elit, vel bibendum elit elit vel elit.</p>
</div>
.box {
min-height: 50%;
border: 1px solid black;
}
In this example, the div element will have a minimum height of 50% of its parent element's height. If the content inside the div is less than 50% of the parent element's height, the div will still be 50% tall. If the content is more than 50% of the parent element's height, the div will expand to fit the content.
In this example, we'll set a min-height of 200 pixels on a div element and add the overflow property:
<div class="box">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed euismod, velit eget bibendum bibendum, velit elit bibendum elit, vel bibendum elit elit vel elit.</p>
</div>
.box {
min-height: 200px;
border: 1px solid black;
overflow: auto;
}
In this example, the div element will have a minimum height of 200 pixels. If the content inside the div is less than 200 pixels, the div will still be 200 pixels tall. If the content is more than 200 pixels, the div will expand to fit the content and a scrollbar will appear to allow the user to scroll through the content.
Min-height is a useful CSS property for creating flexible layouts that can adapt to different amounts of content. By setting a minimum height, you can ensure that your elements are always at least a certain size, while still allowing them to expand to fit larger amounts of content. With the addition of the overflow property, you can also control how content that exceeds the minimum height is displayed.