CSS `height` Property: Controlling Element Height and Handling Content Overflow
Learn how to use the CSS `height` property to precisely control the height of HTML elements. This tutorial explains different ways to set height (length values, percentages, `auto`), discusses handling content overflow, and demonstrates using `min-height` and `max-height` for creating responsive and well-structured web layouts.
Understanding the CSS `height` Property
Setting Element Height with `height`
The CSS `height` property sets the height of an element's content area. This is the space *inside* the element's padding, border, and margin. The height excludes padding, borders, and margins. It accepts length values (like pixels, centimeters, etc.) and percentage values, but not negative values.
`height` Property Values and Behavior
The `height` property's value determines how the height is set:
Value | Description |
---|---|
auto |
(Default) The browser automatically calculates the height based on the content. |
length (e.g., 300px , 10cm ) |
Specifies a fixed height using length units. |
percentage (e.g., 50% ) |
Specifies the height as a percentage of the containing element's height. |
initial |
Resets the property to its default value (auto ). |
inherit |
Inherits the height value from its parent element. |
If the height isn't explicitly set (using a length or percentage), and the element isn't absolutely positioned (`position: absolute;`), the height will default to `auto`.
If content overflows the specified height, you can control how this overflow is handled using the `overflow` property (e.g., `overflow: hidden;`, `overflow: scroll;`). `min-height` and `max-height` properties can also be used to set minimum and maximum height constraints.
`height` Property Syntax
The basic syntax is:
height: auto | length | percentage | initial | inherit;
Examples of Using `height`
Using `auto` and Length Units
CSS Code
/* height: auto; (browser determines height) */
div { height: auto; }
/* height: 320px; (fixed height) */
div { height: 320px; }
/* height: 16em; (height relative to the font size) */
div { height: 16em; }
Using Percentage
CSS Code
div { height: 65%; } /* height is 65% of the parent container's height */
These examples show how you can set the height of a div element using different values for the `height` property.