The height and width properties in CSS are used to define the size of an element. These properties are essential for structuring web pages, ensuring elements fit correctly within their container, and creating responsive designs.
CSS provides multiple ways to control an element’s size. The dimensions can be fixed, responsive, or relative based on the parent element, viewport, or content.
Dimension Type | Description | Example |
---|---|---|
Fixed (px ) |
The element has a strict width/height in pixels. | width: 300px; height: 200px; |
Percentage (% ) |
The element’s size is relative to its parent’s size. | width: 50%; height: 80%; |
Viewport Units (vw , vh ) |
Based on the browser window size. | width: 100vw; height: 100vh; |
Auto (auto ) |
The size adjusts according to the content. | width: auto; height: auto; |
px
)The simplest way to define an element’s size is using px
values.
div {
width: 300px;
height: 200px;
background-color: lightblue;
}
💡 Effect: The <div>
will always be 300px wide and 200px tall, regardless of screen size.
%
)Percentages make an element’s size dependent on its parent container.
div {
width: 50%;
height: 50%;
background-color: lightcoral;
}
✅ If the parent container is 1000px wide, this <div>
will be 500px wide.
vw
, vh
)Viewport units make elements adapt to screen size.
div {
width: 100vw; /* Full screen width */
height: 100vh; /* Full screen height */
background-color: lightgreen;
}
💡 100vw
= 100% of the screen width
💡 100vh
= 100% of the screen height
max-width
and max-height
These properties prevent elements from growing too large.