Creating a Sidebar Menu
A sidebar menu is a vertical navigation bar usually placed on the left or right side of a web page. You can create one using a nav or aside element combined with various CSS layout methods.
Sidebars can be quite useful for websites that have many navigation links or require a clear, consistent list of destinations regardless of where the user is on the page. There are three common ways to build them: using fixed positioning, flexbox, or CSS grid.
Option 1: Fixed Positioning
The' "classic" way to create a sidebar is by using the position property with the fixed value. This method "floats" the sidebar on top of the viewport so it stays in place while you scroll the rest of the page:
When using this method, remember to add a margin-left to your main content container that matches the width of your sidebar. Otherwise, the sidebar will sit on top of your content.
Here's a working example:
Option 2: Using Flexbox
A modern way to create a sidebar is with flexbox. By wrapping the sidebar and the main content in a container with display: flex, you can easily ensure they stay side-by-side without needing absolute or fixed positioning:
This method is excellent for simple layouts where the sidebar and the content should both move up and down together as the user scrolls:
Option 3: Using CSS Grid
CSS grid provides the most robust way to define a clear 2-column structure. By using grid-template-columns, you can define exactly how much space the sidebar takes up and let the main content handle the rest:
Grid is generally considered the best layout method for complex layouts because it gives you total control over the columns and rows of your site.
Here's a full page example using CSS grid: