How to create a vertical menu with CSS?


Vertical menus on a web page are mainly placed on the left or the right. These left or right menus are vertically aligned to make it easier for users to navigate or click them. To create a vertical menu, set a container and within that set the menu links. The display property is to be set as block to let the menu appear vertically. Let us see how to create a vertical menu with HTML and CSS.

Set a container for the menu

A div is set for the menu. The menu links are added using the <a> element with the href attribute −

<div class="Menu">
   <a href="#" class="links selected">About Us</a>
   <a class="links" href="#">Social Links</a>
   <a class="links "href="#">Visit Us</a>
   <a class="links" href="#">More info</a>
   <a class="links" href="#">Phone Number</a>
</div>

Set the width of the menu

The width property is used to set the width’s menu −

.Menu {
   width: 200px;
}

Align the menu vertically

To align our menu vertically, use the display property with the value block. Also, to remove the underline from the menu link, set the text-decoration property to none −

.links {
   background-color: rgb(251, 255, 188);
   color: black;
   display: block;
   padding: 12px;
   text-decoration: none;
}

The link hover color

When the mouse cursor is hovered over the menu link, the color changes. This is set using the background-color property −

.links:hover {
   background-color: rgb(85, 85, 85);
   color:white;
}

The selected link

On a menu, the selected link should always have a different color. Set the background color using the background-color property −

.links.selected {
   background-color: rgb(0, 0, 0);
   color: white;
}

Example

The following is the code to produce a vertical menu with CSS −

<!DOCTYPE html>
<html>
<head>
   <style>
      .Menu {
         width: 200px;
      }
      .links {
         background-color: rgb(251, 255, 188);
         color: black;
         display: block;
         padding: 12px;
         text-decoration: none;
      }
      .links:hover {
         background-color: rgb(85, 85, 85);
         color:white;
      }
      .links.selected {
         background-color: rgb(0, 0, 0);
         color: white;
      }
   </style>
</head>
<body>
   <div class="Menu">
      <a href="#" class="links selected">About Us</a>
      <a class="links" href="#">Social Links</a>
      <a class="links "href="#">Visit Us</a>
      <a class="links" href="#">More info</a>
      <a class="links" href="#">Phone Number</a>
   </div>
</body>
</html>

Updated on: 14-Dec-2023

621 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements