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

ตั้งค่าจำนวนคอลัมน์ที่จะครอบคลุมด้วยแอตทริบิวต์ span ใน HTML

แอตทริบิวต์ span ใช้กับแท็ก <col> ภายใน <colgroup> เพื่อกำหนดจำนวนคอลัมน์ที่ต้องการให้ใช้สไตล์หรือแอตทริบิวต์ร่วมกัน ลดความซ้ำซ้อนของโค้ด

โครงสร้างพื้นฐาน

<table>
  <colgroup>
    <col span="2" style="background-color: #f0f0f0">
    <col style="background-color: #e0e0ff">
  </colgroup>
  <tr><th>หัว 1</th><th>หัว 2</th><th>หัว 3</th></tr>
  <tr><td>ข้อมูล</td><td>ข้อมูล</td><td>ข้อมูล</td></tr>
</table>

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

<!DOCTYPE html>
<html>
<head>
  <style>
    table, th, td { 
      border: 1px solid black; 
      border-collapse: collapse;
      padding: 8px;
    }
  </style>
</head>
<body>
  <table>
    <colgroup>
      <col span="1" style="background-color: #f5f5f5">
      <col span="2" style="background-color: #e8f5e9">
    </colgroup>
    <tr>
      <th>ลำดับ</th>
      <th>ชื่อ</th>
      <th>สถานะ</th>
    </tr>
    <tr>
      <td>1</td>
      <td>อ米特</td>
      <td>ใช้งาน中</td>
    </tr>
    <tr>
      <td>2</td>
      <td>สมชาย</td>
      <td>หยุดชั่วคราว</td>
    </tr>
  </table>
</body>
</html>

แอตทริบิวต์อื่นของ <col>

นอกจาก span แล้ว <col> ยังรองรับ:

  • style - CSS inline styles
  • width - ความกว้างคอลัมน์ (px, %, em)
  • align - จัดตำแหน่ง (left, center, right, justify, char) ล้าสมัย
  • valign - จัดตำแหน่งแนวตั้ง (top, middle, bottom, baseline) ล้าสมัย
แนะนำ: ใช้ CSS nth-child() หรือ nth-of-type() แทน เพื่อแยกสไตล์ออกจาก HTML ได้

ตัวอย่างด้วย CSS แทน

<style>
  table { border-collapse: collapse; width: 100%; }
  td, th { border: 1px solid #ddd; padding: 8px; }
  /* คอลัมน์แรก */
  tr td:first-child, tr th:first-child { background-color: #f5f5f5; }
  /* คอลัมน์ที่ 2-3 */
  tr td:nth-child(2), tr td:nth-child(3),
  tr th:nth-child(2), tr th:nth-child(3) { background-color: #e8f5e9; }
</style>

สรุป

span ใน <col> มีประโยชน์สำหรับตารางใหญ่ที่ต้องการจัดกลุ่มคอลัมน์หลายคอลัมน์ให้มีลักษณะเดียวกัน แต่ในปัจจุบันมักนิยมใช้ CSS Selectors แทนเพื่อความยืดหยุ่นและแยกความรับผิดชอบ (separation of concerns)