max-height
Definition
The max-height property sets the maximum height that an element can have. If the element's content is larger than the specified max-height, the overflow will be clipped. This property is often used in conjunction with overflow to control how content that overflows an element is handled.
Examples
Setting a maximum height for a div element:
div {
max-height: 200px;
overflow: auto;
}
Setting a maximum height for an image element:
img {
max-height: 100%;
}
Setting a maximum height for a table element:
table {
max-height: 400px;
overflow-y: scroll;
}
Values
Value | Description |
---|---|
none | Default value. The element can be sized as large as necessary |
<length> | Specifies the maximum height in pixels, or other absolute or relative units |
<percentage> | Specifies the maximum height as a percentage of the containing block |
Best Practices
- Use max-height with overflow to control how content that exceeds the maximum height of an element is handled.
- Avoid using max-height on elements that need to grow dynamically to fit their content, such as text blocks. Use height instead, or consider setting a minimum height with min-height.
- Use relative units like % and em instead of absolute units like px to ensure that the element scales appropriately across different devices.
- When using max-height on tables, ensure that the table header and footer are visible and that the table body scrolls, not the entire table.
- Test your code in multiple browsers to ensure cross-browser compatibility.
Browser Compatibility
Chrome | Firefox | Safari | Internet Explorer | Microsoft Edge | Opera |
---|---|---|---|---|---|
Yes | Yes | Yes | Yes | Yes | Yes |