CSS Height / Width
CSS Height / Width
The height and width properties are used to control the size of elements. They define how tall and how wide an element should be.
These properties are especially important when building layouts and aligning elements.
Height and Width
You can set fixed sizes using length values such as pixels.
.box {
width: 300px;
height: 150px;
}
Percent values are calculated relative to the parent element.
.container {
width: 500px;
}
.box {
width: 50%;
height: 100px;
}
Auto Values
By default, height and width are set to auto. This allows elements to size themselves based on their content.
.box {
width: auto;
height: auto;
}
Min and Max Width
The min-width and max-width properties set limits on how small or large an element can be.
.box {
min-width: 200px;
max-width: 600px;
}
This is useful for responsive layouts where elements need flexibility.
Min and Max Height
The min-height and max-height properties work the same way for height.
.box {
min-height: 150px;
max-height: 400px;
}
Height and box-sizing
When padding and borders are added, they can increase the total size of an element unless box-sizing: border-box is used.
.box {
width: 300px;
height: 200px;
padding: 20px;
box-sizing: border-box;
}
With this setup, the element remains exactly 300px by 200px.
Code Challenge
Goal: Control the size of the card using height and width properties.
HTML:
<div class="card"> <h3>Size Control</h3> <p>This card has controlled dimensions.</p> </div>
Task:
- Set a fixed width for the card
- Ensure the card never becomes too small
- Add padding without breaking the layout
Try a Solution:
.card {
width: 420px;
min-width: 300px;
padding: 20px;
box-sizing: border-box;
border: 1px solid #ddd;
border-radius: 12px;
}
What’s Next?
Next, you will learn how all these properties work together in the CSS box model.