CSS Units
1 April 2025 | Category: CSS
CSS units define the size of elements, text, margins, padding, and more. These units are categorized into absolute and relative units.
🔹 1. Types of CSS Units
CSS has two main types of units:
1️⃣ Absolute Units → Fixed size (px, cm, mm, in, pt, pc)
2️⃣ Relative Units → Dynamic size based on elements (%, em, rem, vw, vh, etc.)
🔹 2. Absolute Units (Fixed Size)
Absolute units do not change based on screen size or parent elements.
Unit | Description |
---|---|
px | Pixels (most commonly used) |
cm | Centimeters |
mm | Millimeters |
in | Inches (1 in = 2.54 cm) |
pt | Points (1 pt = 1/72 of an inch) |
pc | Picas (1 pc = 12 pt) |
Example
div {
width: 200px; /* Fixed width in pixels */
height: 5cm; /* Fixed height in centimeters */
}
📌 Best Practice → Use px for most layouts, as other absolute units are rarely used.
🔹 3. Relative Units (Flexible & Responsive)
Relative units change based on parent elements or viewport size.
1️⃣ Percentage (%)
📌 Relative to the parent element’s size.
div {
width: 50%; /* 50% of parent width */
height: 80%; /* 80% of parent height */
}
✅ Use case → Flexible layouts (adjusts based on parent size).
2️⃣ em (Relative to Parent Font Size)
📌 1em = Parent element’s font size
p {
font-size: 20px;
}
span {
font-size: 1.5em; /* 1.5 * 20px = 30px */
}
✅ Use case → Text scaling within components.
3️⃣ rem (Relative to Root Font Size)
📌 1rem = Root element’s font size (html
tag)
html {
font-size: 16px;
}
h1 {
font-size: 2rem; /* 2 * 16px = 32px */
}
✅ Use case → Consistent text sizing across elements.
4️⃣ vw & vh (Viewport Width & Height)
📌 Based on browser viewport size.
Unit | Description |
---|---|
vw | 1vw = 1% of viewport width |
vh | 1vh = 1% of viewport height |
div {
width: 50vw; /* 50% of the viewport width */
height: 30vh; /* 30% of the viewport height */
}
✅ Use case → Fullscreen layouts, hero sections.
5️⃣ vmin & vmax (Smallest & Largest Viewport Dimension)
Unit | Description |
---|---|
vmin | 1vmin = 1% of the smallest viewport dimension (width or height) |
vmax | 1vmax = 1% of the largest viewport dimension (width or height) |
div {
width: 10vmin; /* 10% of the smaller dimension */
height: 10vmax; /* 10% of the larger dimension */
}
✅ Use case → Responsive scaling based on different screen sizes.
6️⃣ ch (Relative to Character Width)
📌 1ch = width of the “0” (zero) character in the current font.
p {
width: 20ch; /* Approx. 20 characters wide */
}
✅ Use case → Setting text width for readability.
7️⃣ ex (Relative to x-height of Font)
📌 1ex = height of lowercase “x” in the current font.
p {
line-height: 2ex;
}
✅ Rarely used → Mostly useful for typography adjustments.
🔹 4. Which CSS Unit to Use?
✅ Use px
for precise layout elements.
✅ Use %
for flexible width & height.
✅ Use rem
for consistent typography.
✅ Use vw
& vh
for full-screen sections.
✅ Use em
for scalable components.