แท็ก <center> ใน HTML คืออะไร?
แท็ก <center> ใช้สำห จัดเนื้อหาให้อยู่กึ่งกลางแนวนอน (Horizontal Center)** แต่ แท็กนี้ล้าสมัย (Deprecated) ใน HTML5 แล้ว** ควรใช้ CSS แทน
ตัวอย่าง (โค้ดเก่า - ไม่ควรใช้)
<!DOCTYPE html>
<html>
<head>
<style> table, th, td { border: 2px solid blue; border-collapse: collapse; } </style>
</head>
<body>
<table>
<center>ตารางคำนวณงบประมาณ</center>
<caption>ค่าใช้จ่าย</caption>
<tr><th>หมวดหมู่</th><th>ค่าใช้จ่าย</th></tr>
<tr><td>พัฒนาผลิตภัณฑ์</td><td>500,000</td></tr>
<tr><td>การตลาด</td><td>500,000</td></tr>
<tr><td>บริการ</td><td>100,000</td></tr>
<tr><td>สนับสนุน</td><td>100,000</td></tr>
<tr><td>บำรุงรักษา</td><td>100,000</td></tr>
<tr><td colspan="2">งบประมาณรวม = 1,300,000 บาท</td></tr>
</table>
</body>
</html>
วิธีที่ถูกต้องใน HTML5: ใช้ CSS
1. จัดข้อความ/อินไลน์ให้กึ่งกลาง
.center-text { text-align: center; }
<p class="center-text">ข้อความกึ่งกลาง</p> <div class="center-text"><img src="..." alt="..."></div>
2. จัดบล็อก (Block Element) ให้กึ่งกลาง
.center-block {
display: block;
margin-left: auto;
margin-right: auto;
width: fit-content; /* หรือระบุความกว้าง */
}
<table class="center-block">...</table> <div class="center-block">บล็อกกึ่งกลาง</div>
3. Flexbox (Modern)
.center-flex {
display: flex;
justify-content: center; /* แนวนอน */
align-items: center; /* แนวตั้ง */
}
4. Grid (Modern)
.center-grid {
display: grid;
place-items: center;
}
สรุปการแทนที่
| แท็กล้าสมัย | CSS แทนที่ |
|---|---|
<center> | text-align: center; (inline/text), margin: 0 auto; (block) |
align="center" (บน td, th, div, p) | text-align: center; |
valign="middle" | vertical-align: middle; / Flex/Grid |
จุดสำคัญ
<center>เป็น Block Element (มี Line Break ก่อน/หลัง)- ลบออกจาก HTML5 แล้ว Validator จะแจ้ง Error
- ใช้ CSS แยก Presentation ออกจาก Structure
<caption>บน Table ยังคงใช้ได้ (Semantic) จัดตำแหน่งด้วยcaption-side