บทความนี้จะแนะนำวิธีการสร้างเมนูนำทางด้านข้างที่คงที่บนหน้าจอ (Fixed Side Navigation) โดยใช้ CSS เพียงอย่างเดียว ซึ่งเหมาะสำหรับ Dashboard หรือ Admin Panel ที่ต้องการให้เมนูอยู่ที่เดิมตลอดเวลาแม้จะเลื่อนหน้าเว็บ
ตัวอย่างโค้ด
<!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { margin: 0px; margin-top: 10px; padding: 0px; } nav { height: 100vh; width: 200px; position: fixed; z-index: 1; top: 0; left: 0; background-color: rgb(39, 39, 39); overflow: auto; height: 100%; } .links { display: block; text-align: center; padding: 14px; color: rgb(178, 137, 253); text-decoration: none; font-size: 17px; } .links:hover { background-color: rgb(100, 100, 100); } input[type="text"] { float: right; padding: 6px; margin-top: 8px; margin-right: 8px; font-size: 17px; } .selected { background-color: rgb(0, 18, 43); } </style> </head> <body> <nav> <a class="links selected" href="#"> Home</a> <a class="links" href="#"> Login </a> <a class="links" href="#">Register</a> <a class="links" href="#">Contact Us</a> <a class="links" href="#">More Info</a> </nav> </body> </html>
คำอธิบายโค้ดสำคัญ
- position: fixed; - ทำให้ nav คงที่บนหน้าจอ ไม่เลื่อนตามเนื้อหา
- height: 100vh; - ความสูงเต็มหน้าจอ (viewport height)
- width: 200px; - ความกว้างคงที่ 200 พิกเซล
- z-index: 1; - ให้อยู่เหนือเนื้อหาอื่นๆ
- overflow: auto; - ให้เลื่อนได้ภายในเมนูหากเมนูยาวเกินหน้าจอ
ผลลัพธ์
โค้ดจะสร้างแถบเมนูด้านซ้ายสีเข้ม พร้อมลิงก์สีม่วงอ่อน ที่คงที่ตำแหน่งขณะเลื่อนหน้าเว็บ