The max-height property in CSS limits the maximum height of an element to a specified value. It prevents the element from expanding beyond the defined height, even if the content exceeds it.
Syntax
max-height: <value>;
Value Types
- Length values:
px(pixels): Absolute unit, specific number of pixels.em: Relative unit, based on the font size of the parent element.rem: Relative unit, based on the root element’s font size.%: Relative unit, based on the height of the parent element.vh: Viewport height unit, equal to 1% of the viewport height.vw: Viewport width unit, equal to 1% of the viewport width.
- Keyword values:
none: No maximum height limit.inherit: Inherits themax-heightvalue from the parent element.initial: Sets themax-heightvalue to its default value (which isnone).unset: Resets themax-heightvalue to its initial or inherited value.
Example
.container {
max-height: 300px;
}
This code sets the maximum height of the element with the class container to 300 pixels. If the content of the element exceeds 300 pixels, it will be clipped or overflowed, depending on the overflow property.
Key Points
max-heightworks in conjunction with theheightproperty. Ifheightis set to a value that exceedsmax-height, themax-heightvalue takes precedence.- If
max-heightis set tonone, there is no maximum height limit. - If
max-heightis set toinherit, the value is inherited from the parent element. - If
max-heightis set toinitialorunset, the value is reset to its default or inherited value.
Additional Considerations
- For responsive design, consider using relative units like
em,rem,vh, orvwto ensure themax-heightadapts to different screen sizes. - If you want to prevent overflow while still allowing the element to scroll, set the
overflowproperty toautoorscroll.