สร้าง Side Navigation Menu ที่ตอบสนองตามขนาดหน้าจอ (Responsive) ด้วย CSS Media Queries
ตัวอย่างโค้ด
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> body { margin: 0; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } nav { margin: 0; padding: 0; width: 150px; background-color: #2f77e4; position: fixed; height: 100%; overflow: auto; } nav a { display: block; color: rgb(255, 255, 255); font-weight: bolder; font-size: 20px; padding: 16px; text-decoration: none; } nav a.selected { background-color: rgb(15, 189, 20); color: rgb(255, 255, 255); } nav a:hover:not(.selected) { background-color: white; color: #2f77e4; } div.content { margin-left: 200px; padding: 1px 16px; height: 1000px; } @media screen and (max-width: 700px) { nav { width: 100%; height: auto; position: relative; } nav a {float: left;} div.content {margin-left: 0;} } </style> </head> <body> <nav class="sideBar"> <a class="selected" href="#">Home</a> <a href="#">Login</a> <a href="#">Register</a> <a href="#">Message Us</a> <a href="#">Contact Us</a> </nav> <div class="content"> <h1>Sample Text</h1> <h2>Resize the browser to 700px to change vertical navbar to horizontal navbar</h2> </div> </body> </html>
คำอธิบาย
Desktop (> 700px): Nav คงที่ซ้าย (position: fixed, width: 150px, height: 100%) เนื้อหา margin-left: 200px เว้นที่ให้ nav
Mobile (≤ 700px): Media query เปลี่ยน nav เป็น position: relative, width: 100%, height: auto ลิงก์ float: left กลายเป็นแถบแนวนอน เนื้อหา margin-left: 0
จุดสำคัญของ Responsive Sidebar:
| คุณสมบัติ | Desktop | Mobile |
|---|---|---|
| Position | fixed | relative |
| Width | 150px | 100% |
| Height | 100vh | auto |
| Links | block (stack) | float left (inline) |
| Content margin | 200px | 0 |
รูปแบบ Sidebar อื่นๆ ที่นิยม:
- Off-canvas / Drawer: ซ่อนด้านข้าง คลิกปุ่มแล้ว slide เข้ามา (ต้อง JS)
- Collapsible: ปกติแสดงเต็ม คลิกไอคอนยุบเป็นแค่ icons
- Sticky Sidebar: position: sticky ติดขอบเมื่อ scroll
Modern CSS (ไม่ต้อง float):
@media (max-width: 700px) {
nav { display: flex; flex-wrap: wrap; }
nav a { flex: 1; text-align: center; }
}