CSS Units: px, %, em, rem
CSS uses different types of units to define sizes, spacing, and layout. Understanding units like px
, %
, em
, and rem
helps you create flexible and responsive designs.
1. Pixels (px
)
A pixel is a fixed unit and doesn’t scale. It's great for precise control but not ideal for responsiveness.
p {
font-size: 16px;
margin: 10px;
}
2. Percentages (%
)
Percentages are relative to the parent element’s size.
.container {
width: 80%;
}
img {
width: 100%;
}
Use percentages for fluid layouts that adapt to different screen sizes.
3. em
Units
em
is relative to the font-size of the current element or its parent.
div {
font-size: 16px;
}
p {
font-size: 1.5em; /* 24px if parent is 16px */
}
em
can compound, so use with care when nesting elements.
4. rem
Units
rem
is relative to the root element’s (html
) font-size. It's consistent across all elements regardless of nesting.
html {
font-size: 16px;
}
h1 {
font-size: 2rem; /* 32px */
}
rem
is ideal for scalable and predictable sizing.
Which One to Use?
- px: Precise, but not responsive.
- %: Best for fluid, responsive layouts.
- em: Useful for scalable spacing, but can be tricky with nesting.
- rem: Preferred for font sizes and consistency across the page.
Conclusion
Mastering CSS units is essential for creating responsive, accessible, and flexible designs. Use the right unit based on the layout and scaling behavior you want to achieve.