เรียนรู้วิธีสร้าง Navigation Bar ที่ติดอยู่บนสุดหน้าจอ (Fixed Top Navbar) คงที่ตลอดเวลาแม้จะเลื่อนหน้าเว็บ ใช้ position: fixed และ top: 0
ตัวอย่างโค้ด
<!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:60px; padding: 0px; } nav{ position: fixed; top: 0; width: 100%; background-color: rgb(39, 39, 39); overflow: auto; height: auto; } .links { display: inline-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); } .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> <div class="sample-content"> <h1>Here are some headers</h1> <h2>Here are some headers</h2> <h3>Here are some headers</h3> <h4>Here are some headers</h4> <h1>Here are some headers</h1> <h2>Here are some headers</h2> <h3>Here are some headers</h3> <h4>Here are some headers</h4> </div> </body> </html>
จุดสำคัญ
- body { margin-top: 60px; } - เว้นพื้นที่ด้านบนเท่าความสูง Navbar ไม่然เนื้อหาจะถูกบัง
- nav { position: fixed; top: 0; width: 100%; } - ติดขอบบน กว้างเต็มหน้าจอ
- z-index - ควรเพิ่ม z-index (เช่น 1000) เพื่อให้อยู่เหนือเนื้อหาอื่นๆ
ผลลัพธ์
แถบเมนูสีเข้มติดบนสุด ลองเลื่อนหน้าจูเนื้อหาจะเลื่อนผ่านใต้เมนูได้