CSS
How Do You Set Height and Width as a Percentage in CSS?
Using percentages for height
and width
in CSS is a powerful way to build responsive layouts that adjust to different screen sizes. However, unlike fixed units like px
, percentages behave differently depending on their parent container.
In this article, we’ll explore how percentage-based sizing works, when to use it, and how to avoid common pitfalls.
✅ Setting Width as a Percentage
Setting width is straightforward. It’s based on the width of the parent element.
📌 Example:
.box {
width: 50%;
}
If the parent element is 800px wide, .box
will be 400px wide.
✅ Tip: Percentage widths are relative to the content box of the parent element.
✅ Setting Height as a Percentage
Setting height
is a bit trickier. It also depends on the parent’s height—but only if the parent has an explicitly defined height.
📌 Example:
.parent {
height: 500px;
}
.child {
height: 50%;
}
Here, .child
will be 250px tall (50% of 500px).
⚠️ If the parent’s height is not explicitly set,
height: 50%
won’t work as expected.
🧪 Full Working Example:
<div class="parent">
<div class="child">50% Height & Width</div>
</div>
.parent {
width: 600px;
height: 400px;
background: #f0f0f0;
}
.child {
width: 50%;
height: 50%;
background: #4caf50;
color: white;
text-align: center;
line-height: 200px;
}
In this example:
.child
is 300px wide and 200px tall (50% of its parent).
📐 Percentage vs Viewport Units
Unit | Based on |
---|---|
% | Parent element’s dimensions |
vw/vh | Viewport width and height |
If you want an element to take 100% of the viewport, use 100vw
or 100vh
.
If you want 100% of a container, use 100%
.
🧠 Common Pitfalls and Fixes
❌ Percentage height not working?
✅ Ensure the parent element has a defined height.
html, body {
height: 100%;
}
This is often necessary for layouts that use full-page sections.
✅ Summary
Property | Behavior |
---|---|
width: % | Relative to the parent’s width |
height: % | Relative to the parent’s height (must be set) |
Use case | Responsive containers, fluid layouts |
🚀 Final Thoughts
Percentage-based sizing in CSS is a cornerstone of responsive design. Just remember:
- Width works out of the box.
- Height only works if the parent’s height is defined.
💡 Pro tip: For full-screen layouts, always define
html
andbody
heights when using percentage heights.