Creating a Menu in CSS
In this lesson we will practice creating website menus. Let's make the following menu as an example:
First, we need to make the HTML part. Let's make a div, placing our menu links in it:
<div id="menu">
<a href="#">link text 1</a>
<a href="#">link text 2</a>
<a href="#">link text 3</a>
<a href="#">link text 4</a>
<a href="#">link text 5</a>
</div>
As you can see in the example, one of the menu links is highlighted. It symbolizes that we are on the site page corresponding to this menu item. Such pages are usually highlighted using the active
class:
<div id="menu">
<a href="#">link text 1</a>
<a href="#" class="active">link text 2</a>
<a href="#">link text 3</a>
<a href="#">link text 4</a>
<a href="#">link text 5</a>
</div>
Let's now place our links in a row:
#menu {
display: flex;
}
Let's write the styles of our links:
#menu a {
margin-right: 5px;
padding: 10px;
font: 15px Arial;
text-decoration: none;
color: #1437AD;
border: 1px solid #1437AD;
background-color: white;
}
Let's make links react to hover:
#menu a:hover {
color: blue;
border: 1px solid blue;
background-color: #F5F6FA;
}
The active link style matches the hover link style. Let's combine these styles together:
#menu a:hover, #menu a.active {
color: blue;
border: 1px solid blue;
background-color: #F5F6FA;
}
Let's put the code together and get the code for our menu:
<div id="menu">
<a href="#">link text 1</a>
<a href="#" class="active">link text 2</a>
<a href="#">link text 3</a>
<a href="#">link text 4</a>
<a href="#">link text 5</a>
</div>
#menu {
display: flex;
}
#menu a {
margin-right: 5px;
padding: 10px;
font: 15px Arial;
text-decoration: none;
color: #1437AD;
border: 1px solid #1437AD;
background-color: white;
}
#menu a:hover, #menu a.active {
color: blue;
border: 1px solid blue;
background-color: #F5F6FA;
}