max-height

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 the max-height value from the parent element.
    • initial: Sets the max-height value to its default value (which is none).
    • unset: Resets the max-height value 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-height works in conjunction with the height property. If height is set to a value that exceeds max-height, the max-height value takes precedence.
  • If max-height is set to none, there is no maximum height limit.
  • If max-height is set to inherit, the value is inherited from the parent element.
  • If max-height is set to initial or unset, the value is reset to its default or inherited value.

Additional Considerations

  • For responsive design, consider using relative units like em, rem, vh, or vw to ensure the max-height adapts to different screen sizes.
  • If you want to prevent overflow while still allowing the element to scroll, set the overflow property to auto or scroll.