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

การกำหนดขนาดฟอนต์ด้วย Em ใน CSS

สำหรับขนาดข้อความที่ปรับขยายได้ (scalable) ใช้หน่วย em โดยค่าเริ่มต้น 1em = 16px (หรือ 12pt) ค่าของ em เป็น สัมพัทธ์กับขนาดฟอนต์ของพาเรนต์

ไวยากรณ์ (Syntax)

Selector {
  font-size: /*value*/;
}

ตัวอย่างที่ 1: Div พาเรนต์ 1em, Span ลูก 2em

<!DOCTYPE html>
<html>
<head>
  <style>
    div {
      width: 40%; border: 2px solid yellow; padding: 20px; font-size: 1em;
    }
    span { font-size: 2em; background-color: chartreuse; }
  </style>
</head>
<body>
  <div>
    <p>This is a demo paragraph<span> displaying font sizes</span> set with em in CSS.</p>
  </div>
</body>
</html>

ผลลัพธ์

การกำหนดขนาดฟอนต์ด้วย Em ใน CSS

ตัวอย่างที่ 2: Table 0.8em, Span 1.5em

<!DOCTYPE html>
<html>
<head>
  <style>
    table { width: 40%; border: 2px ridge red; font-size: 0.8em; }
    span { font-size: 1.5em; background-color: silver; }
  </style>
</head>
<body>
  <h2>Class Info</h2>
  <table>
    <tr><th>Number of Students</th></tr>
    <tr><td>Class A</td><td><span>50 Students</span></td></tr>
    <tr><td>Class B</td><td><span>40 Students</span></td></tr>
  </table>
</body>
</html>

ผลลัพธ์

การกำหนดขนาดฟอนต์ด้วย Em ใน CSS

การทำงานของ Em (Compounding Effect)

<div style="font-size: 20px;">       /* 20px */
  <p style="font-size: 1.5em;">     /* 30px (1.5 x 20) */
    <span style="font-size: 1.5em;"> /* 45px (1.5 x 30) ← สะสม! */
  </p>
</div>

Em vs Rem

หน่วยอ้างอิงจากสะสม (Compounding)เหมาะสำหรับ
emพาเรนต์โดยตรงใช่Component scaling, spacing
remRoot (<html>)ไม่Typography system, global sizing

แนวทางแนะนำ

  • ใช้ rem สำหรับ font-size หลัก (heading, body text)
  • ใช้ em สำหรับ spacing (margin, padding) และ component internal scaling
  • ตั้งค่า html { font-size: 100%; } แล้วคิด rem จาก 16px ฐาน