เราสามารถใช้การผสมผสานระหว่าง เปอร์เซ็นต์ (%) และ em เพื่อกำหนดขนาดฟอนต์ขององค์ประกอบ เพื่อความเข้ากันได้ (compatibility) ที่ดีกว่า ทำให้ข้อความมีขนาดสม่ำเสมอข้ามเบราว์เซอร์ต่างๆ
ไวยากรณ์ (Syntax)
Selector {
font-size: /*value*/;
}
ตัวอย่างที่ 1: Body ใช้ % แล้วลูกใช้ em
<!DOCTYPE html>
<html>
<head>
<style>
body { font-size: 80%; } /* 80% ของ 16px = 12.8px */
p { font-size: 2em; } /* 2 x 12.8px = 25.6px */
span { font-size: 4em; font-style: italic; } /* 4 x 12.8px = 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>
ผลลัพธ์

ตัวอย่างที่ 2: Div ใช้ % แล้ว p ใช้ em
<!DOCTYPE html>
<html>
<head>
<style>
div { font-size: 120%; } /* 120% ของ 16px = 19.2px */
p { font-size: 2em; } /* 2 x 19.2px = 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>
ผลลัพธ์

ทำไมต้องผสม % และ em?
- Base size บน Body: ใช้
font-size: 62.5%(เทียบ 10px) หรือ100%(16px) ทำให้คำนวณ em ง่าย - Scale ตามพาเรนต์: em คำนวณจากขนาดฟอนต์ของพาเรนต์ ทำให้ scaling สม่ำเสมอ
- Accessibility: ผู้ใช้ปรับขนาดฟอนต์ใน Browser ได้ผลลัพธ์สัมพัทธ์ถูกต้อง
- Cross-browser: ลดความแตกต่างของ default font size ระหว่างเบราว์เซอร์
แนวทางปฏิบัติแนะนำ (Modern)
:root { font-size: 100%; } /* 16px baseline */
body { font-size: 1rem; } /* ใช้ rem แทน em เพื่อหลีกเลี่ยง compounding */
h1 { font-size: 2.5rem; }
h2 { font-size: 2rem; }
.small { font-size: 0.875rem; }
Rem vs Em: rem อ้างอิง root (html) คงที่ | em อ้างอิงพาเรนต์ สะสมได้ (compounding)