Creating a Navigation Bar
A navigation bar is typically created using a combination of the HTML nav element and a list (ul), then styled with CSS to be horizontal.
Most websites place a navigation bar at the top or side of the page to help users move around. It's often built with a list because navigation links are essentially a "list" of important destinations on a site. By using semantic tags like nav, you also help search engines and screen readers understand that this content is for site navigation.
The HTML Structure
To create a navigation bar, first create the HTML for your menu. Place your links within list items:
By default, this list will appear vertically with bullet points. We'll use CSS to make it look like a real navigation bar.
Basic Horizontal Navbar
To make the list horizontal and remove the bullet points, you can use several methods. One common approach is setting the list items to float: left or using display: inline-block.
Below is a working example that also adds a background color and hover effects:
In this example, we used list-style-type: none to remove bullets, and overflow: hidden on the nav to ensure the background color contains the floating list items.
Using Flexbox for Centered Navigation
A more modern and flexible way to create navbars is using Flexbox. Flexbox is a layout model that allows you to easily align and distribute space among items in a container. This makes it very easy to center your links or space them out evenly without needing to worry about floats or fixed widths.
To center your menu, you can simply apply display: flex and justify-content: center to the element: ul
Navbar with a Logo
Often, you'll want to place a logo (either text or an image) on the left side of the navbar, with the navigation links aligned to the right. Flexbox makes this very easy with the justify-content: space-between property.
In the following example, the logo is placed before the ul element. Because space-between is applied to the nav container, the logo element is pushed to the far left and the list of links is pushed to the far right:
Tip: Keep it Clean
When styling your links, consider removing the default underline with text-decoration: none and adding some padding. This makes the links look more like buttons and provides a larger area for the user to click on, which is especially helpful on touchscreens.