CSS hỗ trợ nhiều đơn vị đo: **Absolute** (cố định) và **Relative** (tương đối).
Bảng tổng hợp đơn vị CSS
| Đơn vị | Loại | Mô tả | Ví dụ |
|---|---|---|---|
% | Relative | Phần trăm so với giá trị tham chiếu (parent, font-size, viewport...) | p { line-height: 150%; } |
cm | Absolute | Centimet (1cm = 37.8px = 25.4/96 in) | div { margin-bottom: 2cm; } |
em | Relative | Font-size của element (hoặc kế thừa). 1em = font-size hiện tại. | p { letter-spacing: 0.1em; } |
ex | Relative | x-height của font (chiều cao chữ 'x' thường). | p { line-height: 3ex; } |
in | Absolute | Inch (1in = 96px = 2.54cm) | p { word-spacing: .15in; } |
mm | Absolute | Milimet (1mm = 3.78px) | p { word-spacing: 15mm; } |
pc | Absolute | Pica (1pc = 12pt = 16px) | p { font-size: 20pc; } |
pt | Absolute | Point (1pt = 1/72 in = 1.333px). Dùng cho print. | body { font-size: 12pt; } (print stylesheet) |
px | Absolute* | CSS Reference Pixel (1px = 1/96 in). Ánh xạ device pixel theo DPR. | p { padding: 25px; } |
vh | Relative | 1% viewport height | h2 { font-size: 3vh; } |
vw | Relative | 1% viewport width | h1 { font-size: 5vw; } |
vmin | Relative | 1% min(vw, vh) | p { font-size: 2vmin; } |
vmax | Relative | 1% max(vw, vh) | div { size: 50vmax; } |
ch | Relative | Chiều rộng ký tự '0' (zero) của font hiện tại. | p { max-width: 60ch; } (optimal line length) |
rem | Relative | Font-size của root element (html). Consistent toàn site. | html { font-size: 16px; } .card { padding: 1rem; } |
lh | Relative | Line-height của element (CSS Level 4). | p { padding: 1lh; } |
rlh | Relative | Line-height của root element (CSS Level 4). | p { margin: 1rlh; } |
Phân loại & Khuyến nghị
- Font-size, spacing, layout:
rem(root-relative),em(local-relative). - Border, border-radius, shadow, outline:
px(cần độ chính xác pixel). - Container width, responsive typography:
vw,vh,vmin,clamp(). - Print stylesheet:
pt,cm,mm,in,pc. - Line length (readability):
ch(60-75ch optimal). - Component internal spacing:
em(scale theo font-size component).
Lưu ý: px trong CSS là "reference pixel", không phải device pixel. Trên màn hình Retina (DPR=2), 1 CSS px = 2 device pixels.