Skip to Content
29 January, 2023

Basic CSS for hamburger menu

Table of Content

/* Hamburger menu button */
.menu-toggle {
  display: none;
  padding: 10px 15px;
  cursor: pointer;
}

/* Hamburger menu icon */
.menu-toggle:before {
  content: "";
  display: block;
  width: 20px;
  height: 2px;
  background-color: #333;
  transition: all 0.3s;
}

/* Transform hamburger menu icon into an X */
.menu-toggle.open:before {
  transform: rotate(45deg);
}
.menu-toggle.open:after {
  transform: rotate(-45deg);
}
.menu-toggle.open:before,
.menu-toggle.open:after {
  position: absolute;
  top: 9px;
  right: 15px;
  content: "";
  display: block;
  width: 20px;
  height: 2px;
  background-color: #333;
}

/* Hide main navigation on mobile */
.main-navigation {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  background-color: #f2f2f2;
  height: 100vh;
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  transition: all 0.3s;
  transform: translateX(-100%);
}

/* Show main navigation on click */
.menu-toggle.open + .main-navigation {
  transform: translateX(0);
}

/* Style navigation links */
.main-navigation a {
  display: block;
  padding: 20px;
  color: #333;
  text-decoration: none;
  transition: all 0.3s;
}
.main-navigation a:hover {
  background-color: #333;
  color: #f2f2f2;
}

This CSS code styles a hamburger menu button, transforms the hamburger menu icon into an X when the menu is open, and hides the main navigation on mobile, showing it on click. You can modify the styles to fit your needs and design preferences.

Insights

The latest from our knowledge base