CSS Units
CSS units define the measurement used for properties like width, height, padding, font-size, margin, etc.
There are two main types:
1. Absolute Units (Fixed Size)
These don’t change based on screen or user settings.
Unit | Description | Example |
---|---|---|
px | Pixels (most common) | font-size: 16px; |
pt | Points (print) | 12pt |
cm , mm , in | Physical lengths (rarely used in web) | 2cm , 1in |
✅ Use px
when you want a fixed size across all devices.
2. Relative Units (Flexible, Responsive)
These adapt to screen size, font size, and other factors.
Unit | Relative To | Example |
---|---|---|
% | Parent element size | width: 80%; |
em | Font size of current element | padding: 2em; |
rem | Font size of root <html> | font-size: 1.5rem; |
vw | 1% of viewport width | width: 50vw; |
vh | 1% of viewport height | height: 100vh; |
🔁 em
vs rem
1em
= 100% of the current element’s font size.1rem
= 100% of the root (html
) font size (more consistent).
Example:
html {
font-size: 16px;
}
p {
font-size: 1.5rem; /* 24px */
}
📐 Example with Units
.container {
width: 80%; /* responsive */
max-width: 1200px; /* limit */
padding: 2rem;
font-size: 1.2em;
height: 100vh;
}
🧠 Best Practices
- Use
%
,vw
, andvh
for layouts and responsiveness. - Use
rem
for scalable and consistent typography. - Avoid
pt
,cm
,in
unless for print styles.