CSS `max-height`: Controlling Maximum Element Height for Responsive Design
Learn how to use the CSS `max-height` property to set maximum height limits for your HTML elements, creating responsive and well-structured layouts. This tutorial explains its functionality, demonstrates its use with different units (pixels, ems, percentages), and discusses handling content overflow when content exceeds the maximum height.
Understanding the CSS `max-height` Property
The CSS `max-height` property sets the maximum height an element can reach. The element's height can be less than the `max-height`, but it won't exceed it. If the content is too large, it will overflow.
How `max-height` Works
Think of `max-height` as setting an upper limit on the element's height. If the content fits within the maximum height, the property has no effect. But if the content is taller, it will be clipped (overflow), and you may need to consider how to handle this overflow (e.g., using scrollbars).
Syntax and Values
The syntax for the `max-height` property is:
max-height: none | length | initial | inherit;
Value Explanations:
none
: (Default) No maximum height limit.length
: Specifies the maximum height using units likepx
,em
,cm
, etc.initial
: Resets the property to its default value (none
).inherit
: Inherits the `max-height` value from its parent element.
Example
This example demonstrates `max-height` with different unit types. The same long text is used in multiple paragraphs, each with a different `max-height`.
p {
max-height: 60px; /* Example 1 */
}
p {
max-height: 6em; /* Example 2 */
}
p {
max-height: 130pt; /* Example 3 */
}
p {
max-height: 5cm; /* Example 4 */
}
In the output, you'll see how the text is clipped (overflows) when it exceeds the specified `max-height`.