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

วิธีสร้าง Floating Layout ใน HTML/CSS

Floating Layout ใช้ CSS float property จัด layout แบบหลายคอลัมน์ (Multi-column) เป็นเทคนิคเก่าแต่ยังใช้ได้ สำหรับ layout เรียบง่าย

หลักการทำงาน

  • float: left - ลอยไปซ้าย เนื้อหาต่อไปจะหุ้มรอบ
  • float: right - ลอยไปขวา
  • clear: both - หยุดการหุ้มรอบ (clearfix)

โครงสร้างคลาสสิก (Sidebar + Content)

<!DOCTYPE html>
<html>
<head>
  <style>
    .container { width: 100%; border: 1px solid green; }
    header, footer { padding: 1em; color: green; background: #fafafa; text-align: left; }
    nav { float: left; max-width: 150px; padding: 1em; }
    nav ul { list-style: none; padding: 0; }
    article { margin-left: 170px; border-left: 1px solid gray; padding: 1em; overflow: hidden; }
    .clearfix::after { content: ""; display: table; clear: both; }
  </style>
</head>
<body>
  <div class="container clearfix">
    <header><h1>Site Title</h1></header>
    <nav>
      <ul>
        <li><a href="#">Link 1</a></li>
        <li><a href="#">Link 2</a></li>
      </ul>
    </nav>
    <article>
      <h2>Main Content</h2>
      <p>Content...</p>
    </article>
    <footer>Footer</footer>
  </div>
</body>
</html>

ปัญหาของ Float Layout

  • Parent height collapse (ต้องใช้ clearfix)
  • Source order ต้องสำคัญ (sidebar ต้องมาก่อน content)
  • Vertical centering ยาก
  • Equal height columns ยาก
  • Responsive ซับซ้อน

Clearfix Pattern (Modern)

.clearfix::after {
  content: "";
  display: table;
  clear: both;
}
/* หรือ */
.container {
  display: flow-root; /* Modern way - ไม่ต้อง clearfix */
}

คำแนะนำ

โปรเจกต์ใหม่ ควรใช้ Flexbox หรือ CSS Grid แทน Float เหมาะสำหรับ: text wrapping รอบรูปภาพ, legacy maintenance, simple cases