× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

How to properly rotate a 3-bar SVG hamburger icon into an X?

Jun 25, 2015
<p>You can remove the JS positioning by using the CSS <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/transform-origin" rel="nofollow"><code>transform-origin</code> property</a>. You can set it on the left of the first and second bars with <code>transform-origin: 0 50%;</code>.</p> <p>This way they will cross each other when they are rotated :</p> <p></p><div class="snippet"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>document.getElementById('burgericon').addEventListener('click', function (e) { this.classList.toggle('open'); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.hamburger { display: block; text-align: center; } svg { cursor: pointer; } .frstbar,.scndbar,.thrdbar { transition: all 0.35s linear; transform: rotate(0deg); transform-origin: 0% 50%; } #burgericon.open .frstbar { transform: rotate(45deg); } #burgericon.open .thrdbar { transform: rotate(-45deg); } #burgericon.open .scndbar { width: 0; opacity: 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;nav class="hamburger"&gt; &lt;svg id="burgericon" xmlns="http://www.w3.org/2000/svg" width="90" height="80"&gt; &lt;g class="icon"&gt; &lt;rect class="frstbar" x="10" y="10" width="70" height="12" rx="7" ry="7" fill="#414141" /&gt; &lt;rect class="scndbar" x="10" y="35" width="70" height="12" rx="7" ry="7" fill="#414141" /&gt; &lt;rect class="thrdbar" x="10" y="60" width="70" height="12" rx="7" ry="7" fill="#414141" /&gt; &lt;/g&gt; &lt;/svg&gt; &lt;/nav&gt; &lt;div&gt; &lt;/div&gt;</code></pre> </div> </div> <p></p> <p>Credits to <a href="http://stackoverflow.com/questions/30941833/how-to-properly-rotate-a-3-bar-svg-hamburger-icon-into-an-x/30942603?noredirect=1#comment49920767_30942603">David Thomas</a> for the JS</p> <p><em>Note that the <code>transform-origin</code> property needs the same vendor prefixes as the <code>transform</code> property. I have omited them for both in the above snippet</em></p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/30941833/How%20to%20properly%20rotate%20a%203-bar%20SVG%20hamburger%20icon%20into%20an%20X?/30942603">Stack Overflow</a>.</p>
comments powered by Disqus