Loading lesson path
Concept visual
Overview
In a horizontal navigation bar, the navigation links are stacked horizontally (next to each other), and is typically aligned on the top of a webpage. The basics of a horizontal navigation bar is an unordered list (<ul>), with list items (<li>), each holding a link (<a>), as shown in the Navbar Intro page. It is also common to add a <nav> element around the <ul> element, that will serve as a container for your navigation bar.
Formula
One way of creating a horizontal navigation bar is to add the float property to the < li >elements. Here we create a basic horizontal navigation bar with a dark background color and change the background color of the links when the user moves the mouse over them:
ul {
list-style-type: none;
margin: 0;
padding: 0;overflow:
hidden;
background-color: #333333;
}
ul li {
float: left;
}
ul li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
ul li a:hover {Formula
background - color:#111111;
}overflow:
hidden;
- Prevents list items from going outside of the list background-color: #333333;
- Adds a black background-color to the <ul> element float: left;Formula
Makes < li > elements float next to each other display: block;Formula
Allows us to specify padding, height, width, and margins to < a >padding: 14px 16px;Formula
Add some padding between each < a > element text - decoration: none;A more modern way of creating a horizontal navigation bar, is to use CSS flexbox.
Formula
The following example creates an equal - looking horizontal navbar as above, but with flexbox:ul {
list-style-type: none;
margin: 0;padding:
0;
background-color: #333333;
display: flex;
}ul li a
{
display: block;
color: white;padding: 14px
16px;
text-decoration: none;
}
ul li a:hover {Formula
background - color:#111111;
}The solution here are display: flex;. This creates a flex context and by default the items are shown from left to right. And just by adding one line to the ul block:
Formula
justify - content:center;, you will have a horizontally centered navbar:ul {
list-style-type: none;
margin: 0;padding:
0;
background-color: #333333;
display: flex;
justify-content: center;
}Here, we add an "active" class to highlight the link corresponding to the current page to let the user know which page/section he/she is on:
Example ul li a.active {
background-color: #04AA6D;
}Here is an example of a gray horizontal navigation bar with a thin, gray border: