CSS มีคุณสมบัติเฉพาะสำหรับจัดสไตล์ตาราง (<table>) และ element ภายใน
คุณสมบัติหลักสำหรับตาราง
| คุณสมบัติ | คำอธิบาย |
|---|---|
border | shorthand ของ border-width, border-style, border-color |
border-collapse | กำหนดว่าเซลล์มีเส้นขอบร่วมกัน (collapse) หรือแยกกัน (separate) |
caption-side | ตำแหน่ง caption (top, bottom) |
empty-cells | แสดง/ซ่อนเซลล์ว่าง (show, hide) - ทำงานเฉพาะ separate |
table-layout | อัลกอริทึม layout: auto (ตามเนื้อหา), fixed (ตาม width ที่กำหนด) |
ตัวอย่างที่ 1: ตารางพนักงานพื้นฐาน
<!DOCTYPE html> <html> <head> <style> body { font-family: 'Bookman Old Style', serif; } th { letter-spacing: 1.9px; } #one { border-right: thick solid blue; } td { text-align: center; } </style> </head> <body> <h2>Employee List</h2> <div> <table> <tr> <th id="one">Employee</th> <th>Department</th> </tr> <tr> <td>John </td> <td>Marketing</td> </tr> <tr> <td>Brad</td> <td>Finance</td> </tr> <tr> <td>Tim </td> <td>IT</td> </tr> <tr> <td>Steve</td> <td>Operations</td> </tr> </table> </div> </body> </html>
ตัวอย่างที่ 2: ตารางขั้นสูง (empty-cells, box-shadow, float)
<!DOCTYPE html> <html> <head> <style> table { float: left; empty-cells: hide; box-shadow: inset 0 0 4px orange; } tr { box-shadow: inset 0 0 10px greenyellow; } td { font-style: italic; box-shadow: inset 0 0 8px red; } table, td { margin: 6px; padding: 6px; border: 1px solid black; } </style> </head> <body> <table> <caption>Demo Table</caption> <tr> <th>Head 1</th> <th>Head 2</th> <th>Head 3</th> </tr> <tr> <td>demo</td> <td></td> </tr> <tr> <td></td> <td></td> <td>demo</td> </tr> <tr> <td></td> <td>demo</td> <td></td> </tr> </table> </body> </html>
คำอธิบายและ Best Practices
Border Collapse - สำคัญที่สุด:
table { border-collapse: collapse; }
ไม่มีช่องว่างระหว่างเซลล์ เส้นขอบรวมกันเป็นเส้นเดียว
Table Layout Fixed - ประสิทธิภาพดีกว่า:
table { table-layout: fixed; width: 100%; }
เบราว์เซอร์คำนวณ layout เร็วขึ้น ไม่ต้องอ่านเนื้อหาทั้งหมดก่อน
Responsive Table:
.table-wrapper { overflow-x: auto; }
table { min-width: 600px; }
Zebra Striping (สลับสีแถว):
tbody tr:nth-child(even) { background-color: #f2f2f2; }
Hover Highlight:
tbody tr:hover { background-color: #e8f4fd; }