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

วิธีแสดงเซลล์ตาราง (Table Cell) ใน HTML

ใช้แท็ก <td> (Table Data) เพื่อแสดงเซลล์ข้อมูลในตาราง แท็ก <td> ใน HTML ใช้สำหรับระบุเซลล์หรือข้อมูลตารางภายในตาราง

แอตทริบิวต์ของแท็ก <td> (ส่วนใหญ่ล้าสมัย)

แอตทริบิวต์ ค่า คำอธิบาย
abbr abbreviated_text Deprecated - ระบุเวอร์ชันย่อของเนื้อหาในเซลล์
align right, left, center, justify, char Deprecated - การจัดตำแหน่งทางสายตา
axis name Deprecated - ระบุหมวดหมู่สำหรับ td นี้
bgcolor rgb, #hex, colorname Deprecated - สีพื้นหลังของเซลล์
char character Deprecated - ตัวอักษรสำหรับจัดตำแหน่ง ใช้เมื่อ align="char"
charoff pixels or % Deprecated - ออฟเซ็ตการจัดตำแหน่ง ใช้เมื่อ align="char"
colspan number ยังใช้ได้ - ระบุจำนวนคอลัมน์ที่เซลล์นี้ครอบคลุม
headers id(s) ระบุรายการ id ของ header cells ที่เกี่ยวข้อง (สำหรับ Accessibility)
height pixels Deprecated - ความสูงของเซลล์
nowrap nowrap Deprecated - ป้องกันการขึ้นบรรทัดอัตโนมัติ
rowspan number ยังใช้ได้ - ระบุจำนวนแถวที่เซลล์นี้ครอบคลุม
scope col, colgroup, row, rowgroup Deprecated ใน td - ใช้กับ <th> แทน
valign top, middle, bottom, baseline Deprecated - การจัดตำแหน่งแนวตั้ง
width pixels or % Deprecated - ความกว้างของเซลล์
💡 สรุปแอตทริบิวต์ที่ยังใช้งานได้ใน HTML5: colspan, rowspan, headers - ที่เหลือควรใช้ 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: #333; color: white; }
    </style>
  </head>
  <body>
    <h3>Result</h3>
    <table>
      <tr>
        <th>Marks</th>
        <th>Student</th>
      </tr>
      <tr>
        <td>600</td>
        <td>Amit</td>
      </tr>
      <tr>
        <td>400</td>
        <td>Anil</td>
      </tr>
    </table>
  </body>
</html>

การใช้ colspan และ rowspan (รวมเซลล์)

<table>
  <tr>
    <th colspan="2">Name</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>
    <td rowspan="2">25</td>
  </tr>
  <tr>
    <td>Jane</td>
    <td>Smith</td>
  </tr>
</table>

แอตทริบิวต์ headers สำหรับ Accessibility

<table>
  <thead>
    <tr>
      <th id="name-header">Name</th>
      <th id="age-header">Age</th>
      <th id="city-header">City</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td headers="name-header">John</td>
      <td headers="age-header">25</td>
      <td headers="city-header">New York</td>
    </tr>
  </tbody>
</table>

การจัดสไตล์ด้วย CSS (แทนแอตทริบิวต์ที่ล้าสมัย)

td {
  text-align: left;        /* แทน align */
  vertical-align: middle;  /* แทน valign */
  padding: 8px;            /* แทน cellpadding */
  background-color: #fff;  /* แทน bgcolor */
  white-space: nowrap;     /* แทน nowrap */
}