In CSS, the height and width properties control how tall and wide an element is. You can size elements using fixed values like px, flexible values like %, or responsive units like vw and vh.
px when you want a box with exact dimensions.width: 100%; to make elements stretch to the parent width.vw / vh to adapt to screen size.max-width / max-height to prevent overflow.height: auto; lets height grow with content.| Property | Description | Example Value |
|---|---|---|
height |
Sets the height of an element. | 200px, 50%, auto |
width |
Sets the width of an element. | 300px, 100%, 50vw |
max-width |
Sets the maximum width of an element. | 500px, 100% |
max-height |
Sets the maximum height of an element. | 500px, 100% |
The basic syntax for setting height and width is simple: you target an element with a selector, then assign values to the properties.
/* Basic syntax for height and width */
selector {
height: value;
width: value;
}
Remember that percentage-based values depend on the size of the parent container, while viewport units (vw, vh) depend on the browser window size.
This example sets a box with a fixed height of 200px and width of 300px.
/* Box with fixed height and width */
.fixed-box {
height: 200px;
width: 300px;
background-color: lightblue;
}
This box stretches to the full width of its container, and the height grows with its content.
/* Full-width box with automatic height */
.full-width {
width: 100%;
height: auto;
background-color: lightgreen;
}
Here, the box width and height are based on the viewport, making it very responsive to screen size.
/* Box sized using viewport width and height */
.vh-vw-box {
width: 50vw;
height: 50vh;
background-color: lightcoral;
}
The box below represents height: 200px; and width: 300px;:
No matter how much content is inside (or how wide the screen is), the outer box keeps these exact dimensions.
A 50vw wide and 50vh tall box will always be half the width and half the height of the browser window. Resize the browser to see such boxes adjust in real projects.
px, %, vw, or vh with numeric values.width: 100%; and height: auto; for responsive images and blocks.max-width with width: 100%; to keep content readable on large screens.<div> with a fixed width of 300px and height of 150px. Add some text and see what happens when the text is very long.width: 100%; and height: auto;. Add an image and observe how it scales.width: 100vw; and height: 100vh;. Place centered text inside it.max-width: 600px; and width: 100%; on a paragraph container to improve readability.px, one with %, and one with vw/vh, then resize the browser and compare their behavior.
/* Starter CSS for experimenting with height and width */
.box-fixed {
width: 300px;
height: 150px;
background-color: lightblue;
}
.box-percent {
width: 80%;
height: auto;
background-color: lightgreen;
}
.box-viewport {
width: 50vw;
height: 30vh;
background-color: lightcoral;
}