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

คุณสมบัติ font-weight ใน CSS (ความหนาของตัวอักษร)

คุณสมบัติ font-weight ใน CSS ใช้กำหนดความหนา (boldness) ของตัวอักษรในองค์ประกอบ

ไวยากรณ์ (Syntax)

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

ตัวอย่างที่ 1: คีย์เวิร์ด normal, bold, bolder

<!DOCTYPE html>
<html>
<head>
  <style>
    div { margin: 3px; font-family: "Ink Free"; width: 30%; font-size: 24px; }
    #one { font-weight: normal; border-bottom: 2px dashed greenyellow; }
    #two { font-family: "Kristen ITC"; font-weight: bolder; border-bottom: 2px dashed cornflowerblue; }
    #three { font-weight: bold; border-bottom: 2px dashed chocolate; }
  </style>
</head>
<body>
  <div id="one">First Demo Text</div>
  <div id="two">Another Demo Text</div>
  <div id="three">Last Demo Text</div>
</body>
</html>

ผลลัพธ์

คุณสมบัติ font-weight ใน CSS (ความหนาของตัวอักษร)

ตัวอย่างที่ 2: ใช้ตัวเลข 100-900 และ Attribute Selector

<!DOCTYPE html>
<html>
<head>
  <style>
    [class|="lis"] { font-style: italic; font-weight: bold; }
    li[class|="lis-ul"] {
      background-color: cadetblue; font-family: Helvetica;
      font-weight: 100; color: gainsboro; width: 20%;
    }
  </style>
</head>
<body>
  <h2>Tutorials</h2>
  <ol>
    <li><p>C#</li>
    <li class="lis-ul-2">DBMS</li>
    <li class="lis-3">OS</li>
    <li>Java</li>
    <ul>
      <li class="lis-ul-one">Core Java</li>
      <li class="lis">Advance Java</li>
    </ul>
  </ol>
</body>
</html>

ผลลัพธ์

คุณสมบัติ font-weight ใน CSS (ความหนาของตัวอักษร)

ค่าของ font-weight

ค่าคำอธิบายตัวเลขเทียบเท่า
normalปกติ400
boldหนา700
bolderหนากว่าพาเรนต์ขึ้นไป 1 ระดับ
lighterบางกว่าพาเรนต์ลง 1 ระดับ
100 - 900ระดับความหนา 9 ระดับ100 (Thin) - 900 (Black)

ข้อสังเกตสำคัญ

  • ฟอนต์ต้องรองรับน้ำหนัก (weight) ที่ต้องการ มิฉะนั้น Browser จะ mapping ให้เอง (เช่น 400/700)
  • Variable Fonts รองรับทุกค่า 1-1000 ได้เรียบร้อย
  • bolder/lighter คำนวณจากพาเรนต์ ไม่ใช่ค่าคงที่