π What Is the Percentage Unit in CSS?
The % (percentage) unit in CSS represents a value relative to another measurement β usually the parent elementβs size. Percentages make layouts flexible, fluid, and responsive.
Note
β Behaves differently depending on the property
β Creates fluid, scalable UI components
π How Percentage Works
A percentage is calculated relative to a reference value. The reference depends on the CSS property being used.
| Property | Relative To |
|---|---|
| width | Parent width |
| height | Parent height |
| padding | Parent width (β even vertical padding) |
| margin | Parent width |
| transform: translate | Element's own size |
| background-position | Background positioning area |
Note
π¦ 1. Percentage for Width
Width Example
.box {
width: 50%; /* Half of the parent width */
}If the parent is 800px β width = 400px.
π 2. Percentage for Height
Percentage heights work ONLY when the parent has an explicit height.
Height Example
.parent {
height: 400px;
}
.child {
height: 50%; /* = 200px */
}Note
π§ 3. Percentage for Padding
One of CSSβs strangest rules:padding-top and padding-bottomare calculated based on the parent width.
Padding Example
.square {
width: 50%;
padding-top: 50%; /* Creates a perfect square! */
}This trick is used to create responsive squares and circles.
π 4. Percentage for Margin
Margin Example
.item {
margin-left: 10%; /* 10% of parent width */
}Horizontal and vertical margins both use parent width.
π 5. Percentage in Background Position
Background Position Example
.banner {
background-position: 50% 50%;
}Percentages represent a position relative to the size of the background container.
π 6. Percentage in Transform translate()
Transform Example
.move {
transform: translate(-50%, -50%);
}Here, % is relative to the element itself, not the parent.
Note
left: 50%; top: 50%; transform: translate(-50%, -50%);
π§ͺ Practical Examples
π± Responsive Grid with Percentages
Responsive Columns
.col {
width: 25%;
float: left;
padding: 1%;
}Creates a 4-column grid that scales with screen size.
πΌοΈ Responsive Square Card
Square Card
.card {
width: 30%;
padding-top: 30%; /* Same value makes a perfect square */
background: #eee;
}βοΈ Centering an Element
Centering with translate
.center {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}β οΈ Common Mistakes with Percentages
- β Expecting percentage height to work without parent height
- β Forgetting that padding always uses parent width
- β Misusing % in transforms (relative to element, not parent)
- β Mixing % with fixed px measurements β inconsistent layout
Note
π₯ Summary
The % unit in CSS is one of the most powerful tools for building flexible and responsive layouts. When used correctly, it adapts your UI to any container or screen size.
Learn more βMDN Docs π