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:
- px — fixed size
- % — relative to parent element
- em / rem — size relative to font size
- auto — browser decides the size
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:
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:
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:
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
- width → sets element width
- height → sets element height
- auto → browser determines the height
- % → size depends on parent container
- max/min-width → responsive limitations
- max/min-height → vertical limitations