หัวข้อ 4: Typography

แนวคิดหลัก

Typography คือการจัดการตัวอักษรให้เหมาะกับการอ่านและบุคลิกของเว็บไซต์ เช่น font, ขนาด, น้ำหนัก, ระยะบรรทัด และการจัดแนว ข้อความที่อ่านง่ายช่วยให้ผู้ใช้เข้าใจเนื้อหาได้ดีขึ้น

font-family

font-family กำหนดชนิดฟอนต์ ควรกำหนด font stack เพื่อให้ browser มีตัวเลือกสำรอง

body {
  font-family: "Noto Sans Thai", Arial, sans-serif;
}

Web-safe fonts เช่น Arial, Georgia, Times New Roman, Verdana มักมีในเครื่องผู้ใช้จำนวนมาก

โหลด Google Fonts

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Thai:wght@400;700&display=swap" rel="stylesheet">

แบบ @import

@import url("https://fonts.googleapis.com/css2?family=Noto+Sans+Thai:wght@400;700&display=swap");

โดยทั่วไป <link> มักเหมาะกว่าในด้าน performance

font-size

หน่วยที่ใช้บ่อย:

  1. px: ค่าคงที่
  2. em: อิงจาก font-size ของ parent
  3. rem: อิงจาก root element

แนะนำใช้ rem สำหรับ accessibility เพราะผู้ใช้ปรับขนาดตัวอักษรระดับ browser ได้ง่ายกว่า

body {
  font-size: 1rem;
}

h1 {
  font-size: 2.25rem;
}

line-height

line-height ควบคุมระยะห่างระหว่างบรรทัด ค่าแนะนำสำหรับเนื้อหาอ่านยาวคือ 1.5 ถึง 1.8

p {
  line-height: 1.7;
}

น้ำหนักและรูปแบบตัวอักษร

.title {
  font-weight: 700;
  font-style: normal;
  text-decoration: none;
  text-transform: none;
}

font-weight ใช้ได้ตั้งแต่ 100 ถึง 900 หาก font รองรับ

ระยะตัวอักษรและการจัดข้อความ

.label {
  letter-spacing: 0.04em;
  word-spacing: 0.1em;
  text-align: center;
}

ตัดข้อความยาว

.truncate {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

property ที่เกี่ยวข้อง:

  1. letter-spacing
  2. word-spacing
  3. text-align
  4. text-overflow
  5. white-space

กิจกรรม

ออกแบบ typography scale สำหรับหน้า course landing page โดยกำหนดขนาด h1, h2, p, .caption และ .button

แบบทดสอบหลังเรียน

  1. Font stack คืออะไร
  2. <link> และ @import สำหรับ Google Fonts ต่างกันอย่างไร
  3. rem มีข้อดีอย่างไร
  4. ค่า line-height ที่เหมาะกับการอ่านเนื้อหายาวควรอยู่ประมาณใด
  5. text-overflow: ellipsis ต้องใช้ร่วมกับ property ใดบ้าง

กลับสัปดาห์ที่ 3