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

วิธีกำหนดความกว้างตารางใน HTML5 ด้วย CSS

ใน HTML5 ไม่รองรับ attribute width ของ <table> แล้ว ต้องใช้ CSS property width ผ่าน attribute style หรือ stylesheet แทน

วิธีการ

<table style="width: 100%; border: 1px solid black"> ... </table>
<!-- หรือ -->
<table style="width: 500px"> ... </table>

ตัวอย่างเต็ม

<!DOCTYPE html>
<html>
<head>
  <style>
    th, td {
      border: 1px solid black;
    }
  </style>
</head>
<body>
  <h1>Programming Languages</h1>
  <table style="width:100px; border: 1px solid black">
    <tr>
      <th>Language</th>
      <th>Release Year</th>
    </tr>
    <tr>
      <td>Java</td>
      <td>1995</td>
    </tr>
    <tr>
      <td>Pascal</td>
      <td>1970</td>
    </tr>
  </table>
</body>
</html>

แนวทางปฏิบัติที่แนะนำ

  • ใช้ width: 100% สำหรับตาราง responsive
  • ใช้ max-width เพื่อจำกัดความกว้างสูงสุด
  • หลีกเลี่ยง inline style ในโปรดักชัน ใช้ class + external CSS แทน
  • inline style จะ override global styles