How to create: Subnavigation

Learn how to use CSS to create subnavigation menus.

Subnavigation

Try it yourself

Create subnavigation

Step 1 - Add HTML:

<!-- Load Font Awesome icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Navigation menu -->
<div class="navbar">
  <a href="#home">Home</a>
  <div class="subnav">
    <button class="subnavbtn">About <i class="fa fa-caret-down"></i></button>
    <div class="subnav-content">
      <a href="#company">Company</a>
      <a href="#team">Team</a>
      <a href="#careers">Careers</a>
    </div>
  </div>
  <div class="subnav">
    <button class="subnavbtn">Services <i class="fa fa-caret-down"></i></button>
    <div class="subnav-content">
      <a href="#bring">Bring</a>
      <a href="#deliver">Deliver</a>
      <a href="#package">Package</a>
      <a href="#express">Express</a>
    </div>
  </div>
  <div class="subnav">
    <button class="subnavbtn">Partners <i class="fa fa-caret-down"></i></button>
    <div class="subnav-content">
      <a href="#link1">Link 1</a>
      <a href="#link2">Link 2</a>
      <a href="#link3">Link 3</a>
      <a href="#link4">Link 4</a>
    </div>
  </div>
  <a href="#contact">Contact</a>
</div>

Example explanation:

You can use any element to open the sub-navigation/dropdown menu, such as <button>, <a>, or <p> elements.

Use container elements (such as <div>) to create the sub-navigation menu and add sub-navigation links within it.

Use the <div> element to wrap the button and <div> so that the sub-navigation menu can be positioned correctly with CSS.

Second step - Add CSS:

/* Navigation menu */
.navbar {
  overflow: hidden;
  background-color: #333;
{}
/* Navigation link */
.navbar a {
  float: left;
  font-size: 16px;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
{}
/* Sub-navigation menu */
.subnav {
  float: left;
  overflow: hidden;
{}
/* Sub-navigation button */
.subnav .subnavbtn {
  font-size: 16px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
{}
/* Add a red background color to navigation links when the mouse hovers */
.navbar a:hover, .subnav:hover .subnavbtn {
  background-color: red;
{}
/* Set the style for sub-navigation content - use absolute positioning */
.subnav-content {
  display: none;
  position: absolute;
  left: 0;
  background-color: red;
  width: 100%;
  z-index: 1;
{}
/* Set the style for sub-navigation links */
.subnav-content a {
  float: left;
  color: white;
  text-decoration: none;
{}
/* Add a grey background color when the mouse hovers */
.subnav-content a:hover {
  background-color: #eee;
  color: black;
{}
/* When the mouse hovers over the sub-navigation container, open the sub-navigation content */
.subnav:hover .subnav-content {
  display: block;
{}

Try it yourself