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

คุณสมบัติ CSS font-size กำหนดขนาดฟอนต์

คุณสมบัติ font-size กำหนดขนาดตัวอักษร รองรับหน่วย: px, em, rem, %, pt, cm, keyword (small, large, x-large, ฯลฯ) ค่าเริ่มต้น 16px (หรือ 12pt)

Syntax

Selector { font-size: <value>; }

ตัวอย่างที่ 1: ใช้ em (Relative)

<!DOCTYPE html> <html> <head> <style> div {    margin: auto;    padding: 10px;    text-align: center;    width: 50%;    border: 2px solid;    border-radius: 15%;    font-size: 1.4em; } </style> </head> <body> <div> one <div>two <div>three</div> </div> </div> </body> </html>

ตัวอย่างที่ 2: Keywords และ Percentage

<!DOCTYPE html> <html> <head> <style> p {    font-size: smaller; } #demo {    font-size: initial; } p:last-of-type {    font-size: 200%; } </style> </head> <body> <h2>Demo Heading</h2> <p>This is demo text 1.</p> <p id="demo">This is demo text 2. </p> <p>This is demo text 3.</p> </body> </html>

คำอธิบาย

ตัวอย่างที่ 1: font-size: 1.4em บน div ภายนอก แล้ว nested div ภายในจะสืบทอดและคูณซ้อน (compounding) ทำให้ขนาดใหญ่ขึ้นเรื่อยๆ

ตัวอย่างที่ 2: smaller (เล็กลง 1 ขนาดจาก parent), initial (คืนค่าเริ่มต้น 16px), 200% (ใหญ่ 2 เท่าของ parent)

หน่วยขนาดฟอนต์:

ประเภทหน่วยคำอธิบาย
Absolutepxพิกเซล คงที่ ไม่ยืดหยุ่น
ptพอยต์ (1pt = 1/72 inch) ใช้สำหรับ print
pcไพคา (1pc = 12pt)
cm, mm, inเซนติเมตร, มิลลิเมตร, นิ้ว
Relativeemเทียบกับ font-size ของ element (compounding)
remเทียบกับ root font-size (html) ไม่ซ้อน
%เทียบกับ parent font-size
exเทียบกับ x-height
chเทียบกับความกว้าง '0'
Keywordxx-small - xx-large7 ระดับ: xx-small, x-small, small, medium, large, x-large, xx-large
smallerเล็กลง 1 ขนาดจาก parent
largerใหญ่ขึ้น 1 ขนาดจาก parent
initialคืนค่าเริ่มต้น
inheritสืบทอดจาก parent
unsetinherit ถ้าสืบทอดได้ ไม่งั้น initial

แนวทางปฏิบัติที่ดี (Best Practices):

  • ใช้ rem สำหรับ font-size หลัก (consistent, accessible)
  • ตั้ง html { font-size: 100%; } (16px baseline) แล้วใช้ rem ทุกที่
  • ใช้ em สำหรับ spacing ภายใน component (padding, margin)
  • หลีกเลี่ยง px สำหรับ font-size (ไม่เคารพ user preference)
  • ใช้ clamp() สำหรับ fluid typography: font-size: clamp(1rem, 2vw + 1rem, 2rem);