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

วิธีจัดสไตล์ HTML ด้วยแท็ก div (Block Container)

แท็ก <div> (division) เป็น block-level container ใช้จัดกลุ่ม element หลายตัวเป็น section เพื่อ apply style หรือ layout ร่วมกัน

คุณสมบัติ

  • Block element - ขึ้นบรรทัดใหม่ กว้างเต็ม container
  • ไม่มี semantic meaning (ใช้ <section>, <article>, <aside>, <nav>, <main>, <header>, <footer> แทนเมื่อเหมาะสม)
  • ใช้ร่วมกับ id หรือ class สำหรับ CSS selector

ตัวอย่าง: ใช้ ID Selector

<!DOCTYPE html>
<html>
<head>
  <title>HTML div Tag</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div id="container">
    <p>Welcome to our website. We provide tutorials on various subjects.</p>
  </div>
</body>
</html>

CSS (style.css)

#container p {
  line-height: 1.5;
  margin: 20px;
  padding-bottom: 15px;
  text-align: justify;
  width: 130px;
  color: blue;
}

ตัวอย่าง: Layout ด้วย div (Legacy)

<div class="container">
  <header class="header">Header</header>
  <nav class="sidebar">Sidebar</nav>
  <main class="content">Main Content</main>
  <footer class="footer">Footer</footer>
</div>

Semantic HTML5 Alternative (แนะนำ)

<div class="container">
  <header>Header</header>
  <nav>Navigation</nav>
  <main>Main Content</main>
  <aside>Sidebar</aside>
  <footer>Footer</footer>
</div>

Best Practices

  • ใช้ semantic tags แทน div เมื่อเป็นไปได้ (SEO, Accessibility, Maintainability)
  • div ยังจำเป็นสำหรับ: wrapper, layout containers, non-semantic grouping
  • ใช้ class แทน id สำหรับ styling (id specificity สูงเกินไป)
  • หลีกเลี่ยง divitis (ใช้ div มากเกินไป)