CSS Height & Width

The height and width properties control the size of an element. You can set fixed sizes, responsive sizes, or allow elements to adjust automatically.


Height & Width Syntax

Syntax:

height: value;
width: value;

Common units you can use:


Fixed Width and Height

Example:

.box-fixed {
  width: 200px;
  height: 100px;
  background-color: lightblue;
  border: 2px solid #333;
}

Output:



Using Percentage (%)

Percentage values adjust based on the size of the parent container.

Example:

.box-percent {
  width: 50%;
  height: 150px;
  background-color: coral;
}

Output:



Auto Height

Using height: auto allows the element to grow based on its content.

Example:

.auto-height {
  width: 300px;
  height: auto;
  background-color: lightgreen;
}

Output:

This box adjusts its height automatically based on the content.


Max-Width & Min-Width

max-width prevents an element from becoming too wide. min-width ensures the element never becomes too narrow.

Example:

.responsive-box {
  width: 80%;
  max-width: 400px;
  min-width: 200px;
  background-color: gold;
}

Output:

Resize your browser to see how this box responds.


Max-Height & Min-Height

These properties control how tall an element is allowed to become.

Example:

.scroll-box {
  width: 300px;
  max-height: 120px;
  overflow-y: auto;
  background-color: #ffe6a7;
}

Output:

This box has a maximum height.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer suscipit urna at commodo condimentum.
Suspendisse potenti. Nam elementum iaculis interdum.
This creates a scrollable area when content exceeds the max height.


Summary

HTML Logo