How to Create a Fixed Menu in HTML using CSS
In this tutorial, you will learn how to keep a menu or a navigation bar fixed at the top/bottom in HTML using CSS. So hope you will enjoy learning how to create a fixed menu in HTML with the help of CSS.
You may have come across a fixed menu in several websites. It helps the viewer by making it easy to access the Menu while scrolling through the document/page. The menu stays at the top/bottom of the webpage, overlaying all other content.
To keep a menu fixed to the top of the browser screen, we will need to use the position: fixed
CSS property and the top: 0
/ bottom: 0
CSS property.
Creating a Menu or Nav Bar in HTML
Let’s start by creating a basic menu bar:
<html> <head> <style> .main, body{ margin: 0; padding: 0; } .navbar{ background-color: #333; width: 100%; } </style> </head> <body> <div class="navbar"> <a href="#home">Home</a> <a href="#blog">Blog</a> <a href="#contact">Contact</a> </div> <div class="main"> <p>This is a sample text...</p> </div> </body> </html>
How to Keep the Menu Fixed at the Top using HTML and CSS
Now, to keep this menu fixed at the top of the page, we need to add the properties mentioned before, in the navbar CSS class.
<html> <head> <style> .main, body{ margin: 0; padding: 0; } .navbar{ background-color: #333; width: 100%; position: fixed; top: 0; } </style> </head> <body> <div class="navbar"> <a href="#home">Home</a> <a href="#blog">Blog</a> <a href="#contact">Contact</a> </div> <div class="main"> <p>This is a sample text...</p> </div> </body> </html>
You will notice a change in the webpage: the menu now stays at the top of the page.
Keeping the Menu Fixed at the Bottom
Now, to keep this menu fixed at the bottom of the page, we need to add the properties mentioned before, in the navbar CSS class.
<html> <head> <style> .main, body{ margin: 0; padding: 0; } .navbar{ background-color: #333; width: 100%; position: fixed; bottom: 0; } </style> </head> <body> <div class="navbar"> <a href="#home">Home</a> <a href="#blog">Blog</a> <a href="#contact">Contact</a> </div> <div class="main"> <p>This is a sample text...</p> </div> </body> </html>
You will notice a change in the webpage: the menu now stays at the bottom of the page.
You can check the code running on your browser. This will Create a Fixed Menu in HTML.
Also read:
When creating sample code – PLEASE show it in action!