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

HTML <th> colspan Attribute - รวมหัวข้อคอลัมน์ในตาราง

แอตทริบิวต์ colspan ของแท็ก <th> (table header cell) ใช้ระบุจำนวนคอลัมน์ที่เซลล์หัวข้อนี้ควรครอบคลุม (span across) คล้ายกับ <td colspan> แต่ใช้สำหรับหัวข้อ

รูปแบบการใช้งาน

<th colspan="2">หัวข้อรวม 2 คอลัมน์</th>

ตัวอย่างการใช้งาน

<!DOCTYPE html>
<html>
<head>
  <style>
    table, th, td { 
      border: 2px solid green; 
      border-collapse: collapse;
      padding: 10px;
      text-align: center;
    }
    caption { font-weight: bold; margin-bottom: 10px; font-size: 1.2em; }
  </style>
</head>
<body>
  <h2>ค่าใช้จ่ายผลิตภัณฑ์</h2>
  <table>
    <caption>งบประมาณประจำปี (หน่วย: บาท)</caption>
    <tr>
      <th colspan="2">ค่าใช้จ่าย</th>
    </tr>
    <tr>
      <td>การพัฒนาผลิตภัณฑ์</td>
      <td>500,000</td>
    </tr>
    <tr>
      <td>การตลาด</td>
      <td>500,000</td>
    </tr>
    <tr>
      <td>บริการ</td>
      <td>100,000</td>
    </tr>
    <tr>
      <td>สนับสนุน</td>
      <td>100,000</td>
    </tr>
    <tr>
      <td>บำรุงรักษา</td>
      <td>100,000</td>
    </tr>
    <tr>
      <td colspan="2"><strong>งบประมาณรวม = 1,300,000 บาท</strong></td>
    </tr>
  </table>
</body>
</html>

การจัดโครงสร้างตารางที่ซับซ้อน

สามารถใช้ colspan และ rowspan ร่วมกันได้:

<table>
  <tr>
    <th rowspan="2">หมวดหมู่</th>
    <th colspan="2">ไตรมาส 1</th>
    <th colspan="2">ไตรมาส 2</th>
  </tr>
  <tr>
    <th>รายได้</th><th>ค่าใช้จ่าย</th>
    <th>รายได้</th><th>ค่าใช้จ่าย</th>
  </tr>
  <tr>
    <td>ผลิตภัณฑ์ A</td>
    <td>100</td><td>50</td>
    <td>120</td><td>55</td>
  </tr>
</table>

การเข้าถึง (Accessibility)

  • ใช้ scope="colgroup" ร่วมกับ colspan เพื่อบอก screen reader ว่าหัวข้อนี้ครอบคลุมกลุ่มคอลัมน์
  • ตัวอย่าง: <th colspan="2" scope="colgroup">ไตรมาส 1</th>

ข้อควรระวัง

  • ค่า colspan ต้องเป็นจำนวนเต็มบวก (1, 2, 3...)
  • ต้องลบ <th> หรือ <td> ที่ถูกรวมออกจากแถวนั้น เพื่อไม่ให้จำนวนเซลล์ไม่ตรงกับคอลัมน์อื่น
  • ใช้ร่วมกับ <colgroup> และ <col> สำหรับการจัดสไตล์คอลัมน์ที่ถูกรวม

แนวทางปฏิบัติที่ดีที่สุด

Semantic HTML: ใช้ <thead>, <tbody>, <tfoot> แยกส่วนหัว/เนื้อหา/ท้ายตาราง ร่วมกับ scope และ colspan/rowspan เพื่อตารางที่เข้าถึงได้และ SEO ดี