Chúng ta có thể sử dụng kết hợp phần trăm (%) và em để chỉ định font-size của các phần tử nhằm tương thích font tốt hơn. Điều này cho phép chúng ta có văn bản thống nhất trên các trình duyệt khác nhau.
Cú pháp
selector {
font-size: /* value */;
}
Tại sao kết hợp % và em?
- % trên body/root: Thiết lập baseline tương đối với cài đặt trình duyệt người dùng (accessibility)
- em cho các phần tử con: Tỷ lệ tương đối với parent, scale tự nhiên
- Kết hợp cho hệ thống typography responsive, accessible
Ví dụ 1: Body 80% + p 2em + span 4em
<!DOCTYPE html>
<html>
<head>
<style>
body { font-size: 80%; } /* ~12.8px nếu default 16px */
p { font-size: 2em; } /* 25.6px */
span { font-size: 4em; font-style: italic; } /* 51.2px */
</style>
</head>
<body>
<p>Reading <span>source code</span> written by others gives you opportunity to criticize the mistakes done in writing that code</p>
</body>
</html>
Ví dụ 2: Div 120% + p 2em
<!DOCTYPE html>
<html>
<head>
<style>
div { font-size: 120%; } /* ~19.2px */
p { font-size: 2em; } /* 38.4px */
</style>
</head>
<body>
<h3>Demo Heading</h3>
This is example text.
<div>
Examples are easier to understand with practical implementation
<p>This is another text just to display different ways to set font size in CSS.</p>
</div>
</body>
</html>
Kỹ thuật "62.5% Trick" (Phổ biến)
html { font-size: 62.5%; } /* 10px = 1rem */
body { font-size: 1.6rem; } /* 16px baseline */
/* Dễ dàng tính toán */
h1 { font-size: 3.2rem; } /* 32px */
h2 { font-size: 2.4rem; } /* 24px */
p { font-size: 1.6rem; } /* 16px */
.small { font-size: 1.2rem; } /* 12px */
Ưu điểm: Dễ chuyển đổi px ↔ rem, tinh chỉnh responsive bằng cách đổi html font-size tại breakpoint.
Responsive Typography với clamp()
/* Modern fluid typography - không cần media query */
h1 { font-size: clamp(2rem, 5vw + 1rem, 4rem); }
p { font-size: clamp(1rem, 1.5vw + 0.5rem, 1.25rem); }
Lưu ý
%trênfont-sizetính theo font-size của parentemcũng tính theo parent — lồng nhau nhân chồng (compounding)remtính theo root (html) — tránh compounding- Khuyến nghị: % trên root, rem cho components, em cho internal scaling