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

การสร้างตารางใน HTML

แท็ก <table> ใน HTML ใช้สำหรับกำหนดตาราง แท็ก table จะมีแท็กอื่นๆ ที่กำหนดโครงสร้างของตารางอยู่ภายใน

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

แอตทริบิวต์ ค่า คำอธิบาย
abbr abbreviated_text Deprecated - ระบุเวอร์ชันย่อของเนื้อหาในเซลล์
align right, left, center, justify, char Deprecated - การจัดตำแหน่งทางสายตา
bgcolor rgb(x,x,x), #hexcode, colorname Deprecated - ระบุสีพื้นหลังของตาราง
border Pixels Deprecated - ระบุความกว้างของเส้นขอบ ค่า "0" หมายถึงไม่มีเส้นขอบ
cellpadding pixels or % Deprecated - ระบุระยะห่างระหว่างขอบเซลล์กับเนื้อหา
cellspacing pixels or % Deprecated - ระบุระยะห่างระหว่างเซลล์
frame void, above, below, hsides, lhs, rhs, vsides, box, border Deprecated - ใช้ร่วมกับ border attribute ระบุด้านของเฟรมที่แสดงเส้นขอบรอบตาราง
rules none, groups, rows, cols, all Deprecated - ใช้ร่วมกับ border attribute ระบุกฎที่ปรากฏระหว่างเซลล์ของตาราง
summary Text Deprecated - ระบุสรุปของเนื้อหา
width pixels or % Deprecated - ระบุความกว้างของตาราง
⚠️ หมายเหตุสำคัญ: แอตทริบิวต์ทั้งหมดข้างต้นเป็น Deprecated (ล้าสมัย) แล้วใน HTML5 ควรใช้ CSS สำหรับการจัดรูปแบบตารางแทน เพื่อแยกเนื้อหา (HTML) และการนำเสนอ (CSS) ตามมาตรฐานเว็บสมัยใหม่

ตัวอย่าง: ตารางพื้นฐานพร้อม CSS

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

<!DOCTYPE html>
<html>
  <head>
    <style>
      table, th, td {
        border: 1px solid black;
        border-collapse: collapse;
      }
      th, td {
        padding: 8px 12px;
      }
      th {
        background-color: #f2f2f2;
      }
    </style>
  </head>
  <body>
    <h3>Ranking</h3>
    <table>
      <tr>
        <th>Rank</th>
        <th>Name</th>
      </tr>
      <tr>
        <td>One</td>
        <td>Amit</td>
      </tr>
      <tr>
        <td>Two</td>
        <td>Anil</td>
      </tr>
    </table>
  </body>
</html>

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

สำหรับตารางที่ซับซ้อน ควรใช้โครงสร้างที่มีความหมาย (Semantic):

<table>
  <caption>Monthly Savings</caption>
  <thead>
    <tr><th>Month</th><th>Savings</th></tr>
  </thead>
  <tbody>
    <tr><td>January</td><td>$100</td></tr>
    <tr><td>February</td><td>$80</td></tr>
  </tbody>
  <tfoot>
    <tr><td>Total</td><td>$180</td></tr>
  </tfoot>
</table>