Day 2 - Units in CSS
Understanding methods for sizing elements and adding depth effects.
1. Absolute vs Relative Units
Absolute (px): Fixed size.
Relative (em): Relative to parent font size.
Relative (rem): Relative to root (html) font size.
Code:
/* CSS */
.px-text {
font-size: 20px;
} /* Always 20px */
.em-text {
font-size: 1.5em;
} /* 1.5 x Parent Size */
.rem-text {
font-size: 1.5rem;
} /* 1.5 x Root Size */
Output:
Fixed Units — px
This box is
width: 200px; height: 60px; font-size: 20px. Its
size never changes no matter what the parent or root font-size
is.
Relative Units — em & rem
Parent is font-size: 16px. Each child uses
1.5em — so nesting compounds. The rem box always
resolves to 1.5 × 16px = 24px from the root.
Percentage — %
The blue bar is width: 60%. Resize the window and
it stays at 60% of its parent container.
Viewport Units — vw & vh
The orange bar is width: 50vw — half the browser
window's width. The teal box is height: 30vh — 30%
of the window's height. Resize the browser to see them respond.
rem Reference — Browser Default Font Sizes
The standard browser default font size is 16px, which equals
1rem. All rem values are calculated relative to
that base size.
| Label | px value |
|---|---|
| Very Small |
10px
Live sample text (0.625rem)
|
| Small |
12px
Live sample text (0.75rem)
|
| Medium |
16px
Live sample text (1rem)
|
| Large |
20px
Live sample text (1.25rem)
|
| Very Large |
24px
Live sample text (1.5rem)
|