Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Các đơn vị đo lường (Measurement Units) trong CSS

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ạiMô tảVí dụ
%RelativePhần trăm so với giá trị tham chiếu (parent, font-size, viewport...)p { line-height: 150%; }
cmAbsoluteCentimet (1cm = 37.8px = 25.4/96 in)div { margin-bottom: 2cm; }
emRelativeFont-size của element (hoặc kế thừa). 1em = font-size hiện tại.p { letter-spacing: 0.1em; }
exRelativex-height của font (chiều cao chữ 'x' thường).p { line-height: 3ex; }
inAbsoluteInch (1in = 96px = 2.54cm)p { word-spacing: .15in; }
mmAbsoluteMilimet (1mm = 3.78px)p { word-spacing: 15mm; }
pcAbsolutePica (1pc = 12pt = 16px)p { font-size: 20pc; }
ptAbsolutePoint (1pt = 1/72 in = 1.333px). Dùng cho print.body { font-size: 12pt; } (print stylesheet)
pxAbsolute*CSS Reference Pixel (1px = 1/96 in). Ánh xạ device pixel theo DPR.p { padding: 25px; }
vhRelative1% viewport heighth2 { font-size: 3vh; }
vwRelative1% viewport widthh1 { font-size: 5vw; }
vminRelative1% min(vw, vh)p { font-size: 2vmin; }
vmaxRelative1% max(vw, vh)div { size: 50vmax; }
chRelativeChiều rộng ký tự '0' (zero) của font hiện tại.p { max-width: 60ch; } (optimal line length)
remRelativeFont-size của root element (html). Consistent toàn site.html { font-size: 16px; } .card { padding: 1rem; }
lhRelativeLine-height của element (CSS Level 4).p { padding: 1lh; }
rlhRelativeLine-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.