How to Create a Fixed Menu with CSS

A fixed menu is a navigation bar that stays at the top of a website’s page even when the user scrolls down.

This makes it easier for users to access the navigation links, improving their overall experience on the site.

In this tutorial, we’ll explain how to create a fixed menu using CSS.


Step 1: HTML Markup

To create a fixed menu, you first need to have a basic HTML structure for your navigation bar. Here’s an example:

<header>
  <nav>
    <ul>
      <li><a href="#">Home</a></li>
      <li><a href="#">About</a></li>
      <li><a href="#">Services</a></li>
      <li><a href="#">Contact</a></li>
    </ul>
  </nav>
</header>

Step 2: Adding CSS Styles

Next, you need to add CSS styles to make the navigation bar fixed at the top of the page. Here’s an example:

header {
  position: fixed;
  top: 0;
  width: 100%%;
  background-color: #fff;
  z-index: 999;
}

Explanation of CSS Styles:

  • The position: fixed property positions the element relative to the window, and it will not move when the page is scrolled.
  • The top: 0 property sets the top edge of the element to the top edge of the window.
  • The width: 100% property sets the width of the element to be equal to the width of the window.
  • The background-color: #fff property sets the background color of the element to white.
  • The z-index: 999 property sets the stack order of the element, ensuring that it will be displayed above other elements on the page.

Step 3: Adjusting for Different Screen Sizes

Finally, you may want to adjust the styles for different screen sizes to ensure that the fixed menu looks good on all devices. Here’s an example:

@media screen and (max-width: 767px) {
  header {
    position: relative;
  }
}

Explanation of Media Query:

  • The media query checks the maximum width of the screen.
  • If the screen width is less than 767px, the position property of the header element is set to relative. This makes the navigation bar no longer fixed, allowing it to scroll with the page.

Conclusion

In conclusion, creating a fixed menu with CSS is relatively straightforward and can greatly improve the user experience on your website.

With the basic HTML markup and CSS styles explained in this post, you should be able to create a fixed menu that meets your needs.