Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

การตั้งค่าขนาดฟอนต์ด้วยหน่วย EM ใน CSS

หน่วย em เป็นหน่วยสัมพัทธ์ (relative unit) เทียบกับ font-size ของ element ตัวเอง (หรือสืบทอดจาก parent) โดยค่าเริ่มต้นของบราวเซอร์คือ 1em = 16px

ตัวอย่างที่ 1: กำหนด font-size 1.3em

<!DOCTYPE html>
<html>
<head>
  <style>
    .demo { 
      text-decoration: overline; 
      text-decoration-color: yellow; 
      font-size: 1.3em;  /* ~20.8px หาก root = 16px */
    }
  </style>
</head>
<body>
  <h1>Examination Details</h1>
  <p class="demo">Exam on 20th December.</p>
  <p class="demo2">Exam begins at 9AM.</p>
</body>
</html>

ตัวอย่างที่ 2: ใช้ em สำหรับ font-size ใน div

<!DOCTYPE html>
<html>
<head>
  <style>
    div { 
      text-align: justify; 
      text-justify: inter-word; 
      color: white; 
      background-color: gray; 
      font-size: 1.5em;  /* ~24px */
    }
  </style>
</head>
<body>
  <h2>Demo Heading</h2>
  <div>This is demo text. This is demo text. This is demo text...</div>
</body>
</html>

ข้อดีของ em

  • Scalable: ผู้ใช้ปรับขนาดตัวอักษรในบราวเซอร์ (browser zoom/text size) em จะ scale ตามไปด้วย
  • Relative: เหมาะสำหรับ spacing ที่ควรสัมพันธ์กับ font-size (margin, padding, line-height)
  • Accessible: ตอบสนองการตั้งค่า user preferences

ข้อเสียและข้อควรระวัง

  • Compounding: em สะสมได้ (nested elements) parent: 1.2em; child: 1.2em; → child = 1.44em ของ root
  • Context-dependent: ต้องรู้ font-size ของ parent จึงคำนวณค่าจริงได้

แนวทางปฏิบัติสมัยใหม่: ใช้ REM

rem (root em) อ้างอิงจาก html element (root) เสมอ ไม่สะสม

html { font-size: 16px; }  /* หรือ 100% */
h1 { font-size: 2rem; }    /* 32px เสมอ */
p { font-size: 1rem; }     /* 16px เสมอ */
margin: 1rem;              /* 16px spacing system */

สรุป: ใช้ rem สำหรับ font-size และ spacing system ใช้ em เฉพาะเมื่อต้องการ scale ตาม parent โดยเจตนา (เช่น component ที่มีขนาดตัวอักษรต่างกัน)