Animated hamburger menu icon

Animated hamburger menu icon

by Csaba Hellinger

HTML

<svg viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg">
  <style>
    path {
      fill: none;
      stroke: currentColor;
      stroke-width: var(--stroke-width, 1);
      stroke-linecap: round;
      stroke-linejoin: round;
      transition-property: stroke, stroke-dasharray, stroke-dashoffset, rotate, opacity;
      transition-duration: var(--duration, 400ms);
      transition-timing-function: ease-in-out;
      stroke-dasharray: 8 12;
      transform-origin: center center;
    }
    .isopen path {
      stroke: var(--open-color, currentColor);
    }
    .isopen :where(#top,#bottom) {
      stroke-dasharray: 12 12;
      stroke-dashoffset: -8;
    }
    .isopen #middle {
      opacity: 0;
      rotate: 135deg;
    }    
  </style>  
  <path id="top" d="M 1,1 L 9,1 1,9" />
  <path id="middle" d="M 1,5 L 9,5" />
  <path id="bottom" d="M 1,9 L 9,9 1,1" />      
</svg>

<p>Animated hamburger menu icon. Click to toggle.</p>

CSS

svg {
  --open-color: red;
  --stroke-width: 1.4;
  --duration: 500ms;
  width: 2rem;
  cursor: pointer;
  opacity: 0.8;
}

svg:hover {
  opacity: 1;
}

/* unrelated, jsut for demonstration */

body {
  background: #222;
  color: #fff;
  margin: 1rem;
}

p {
  font-family: sans-serif;
  font-size: 0.9rem;
  opacity: 0.3;
}

JavaScript

const svg = document.querySelector('svg');
svg.onclick = () => svg.classList.toggle('isopen');