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

วิธีสร้างส่วนท้ายตาราง (Table Footer) ใน HTML

แท็ก <tfoot> ใน HTML ใช้สำหรับเพิ่มส่วนท้าย (Footer) ให้กับตาราง แท็ก <tfoot> ใช้ร่วมกับ <tbody> และ <thead> เพื่อกำหนดแต่ละส่วนของตาราง (หัว, ส่วนท้าย, ส่วนเนื้อหา)

แอตทริบิวต์ของ <tfoot> (ล้าสมัย - ควรใช้ CSS)

แอตทริบิวต์ ค่า คำอธิบาย
align right, left, center, justify, char Deprecated - การจัดตำแหน่งทางสายตา
char character Deprecated - ระบุตัวอักษรที่ใช้จัดตำแหน่ง ใช้เมื่อ align="char"
charoff pixels or % Deprecated - ระบุออฟเซ็ตการจัดตำแหน่ง ใช้เมื่อ align="char"
valign top, middle, bottom, baseline Deprecated - การจัดตำแหน่งแนวตั้ง
⚠️ หมายเหตุ: แอตทริบิวต์ข้างต้นล้าสมัยแล้ว ให้ใช้ CSS properties เช่น text-align, vertical-align แทน

ตัวอย่าง

ลองรันโค้ดต่อไปนี้เพื่อสร้างส่วนท้ายตารางใน HTML:

<!DOCTYPE html>
<html>
  <head>
    <style>
      table, td {
        border: 1px solid black;
        border-collapse: collapse;
      }
      th, td {
        padding: 8px 12px;
      }
      thead { background-color: #333; color: white; }
      tfoot { background-color: #f2f2f2; font-weight: bold; }
      tbody tr:nth-child(even) { background-color: #f9f9f9; }
    </style>
  </head>
  <body>
    <table style="width:100%">
      <thead>
        <tr>
          <th colspan="4">This is the head of the table</th>
        </tr>
      </thead>
      <tfoot>
        <tr>
          <td colspan="4">This is the footer of the table</td>
        </tr>
      </tfoot>
      <tbody>
        <tr>
          <td>Cell 1</td><td>Cell 2</td><td>Cell 3</td><td>Cell 4</td>
        </tr>
        <tr>
          <td>Cell 1</td><td>Cell 2</td><td>Cell 3</td><td>Cell 4</td>
        </tr>
      </tbody>
    </table>
  </body>
</html>

ลำดับของ thead, tfoot, tbody ใน HTML

ใน HTML สามารถเขียน <tfoot> ก่อน <tbody> ได้ (เหมือนตัวอย่างข้างต้น) เบราว์เซอร์จะแสดงผลให้ถูกต้อง: thead บนสุด, tbody กลาง, tfoot ล่างสุด

โครงสร้างตารางที่สมบูรณ์ (Complete Table Structure)

<table>
  <caption>Monthly Sales Report</caption>
  <colgroup>
    <col style="width: 30%">
    <col style="width: 20%">
    <col style="width: 25%">
    <col style="width: 25%">
  </colgroup>
  <thead>
    <tr><th>Product</th><th>Q1</th><th>Q2</th><th>Q3</th></tr>
  </thead>
  <tbody>
    <tr><td>Product A</td><td>100</td><td>150</td><td>200</td></tr>
    <tr><td>Product B</td><td>80</td><td>120</td><td>180</td></tr>
  </tbody>
  <tfoot>
    <tr><td>Total</td><td>180</td><td>270</td><td>380</td></tr>
  </tfoot>
</table>

ประโยชน์ของการใช้ thead, tbody, tfoot

  • Accessibility: Screen readers อ่านโครงสร้างได้ชัดเจน
  • Printing: เบราว์เซอร์สามารถพิมพ์ thead/tfoot ทุกหน้าได้
  • Scrolling: CSS สามารถทำให้ tbody scroll ได้แยกจาก thead/tfoot
  • Styling: จัดสไตล์แต่ละส่วนได้อิสระ