How to create a responsive hamburger menu in AMP HTML
Solution 1
AMP now has support for menu using the amp-sidebar component.
Solution 2
I have accomplished this with the use of a :target
pseudoclass.
HTML
<nav id="slide-in-menu">
...nav menu content...
</nav>
<section class="content-section">
<a href="#slide-in-menu">Hamburger Icon</a>
</section>
CSS
#slide-in-menu {
transform: translateX(-100%);
transition: transform .2s ease-in-out;
... additional required styles ...
}
#slide-in-menu:target {
transform: translateX(0);
}
Solution 3
This is not currently possible without major hacks.
Follow along in the feature request bug: https://github.com/ampproject/amphtml/issues/827
Solution 4
You can do this with the :focus pseudo class. Take a look at https://fresnobee.relaymedia.com/amp/news/local/education/article61889207.html for a live example (www.washingtonpost.com also does it this way). Or you could wait for the <amp-sidebar>
tag to go live.
The code looks like
<a id="burger" tabindex="0">☰</a>
<div id="burgerCancel" tabindex="0">☰</div>
<div id="burgerMenu">
<ul>
<li><a href="/news/local/#navlink=ampnav">Local News</a></li>
<li><a href="/sports/#navlink=ampnav">Sports</a></li>
</ul>
</div>
<button id="burgerMask"></button>
and the css
#burger:focus ~ #burgerMenu {
transform: translateY(0px); /* or whatever other way you want it to appear */
}
#burgerMask {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: #000;
z-index: 998;
border: 0;
opacity: 0;
transition: opacity 250ms cubic-bezier(0, .67,0,.67);
pointer-events: none; /*this is important */
}
#burger:focus ~ #burgerMask {
pointer-events: auto;
opacity: 0.7;
display: block;
}
Admin
Updated on July 31, 2022Comments
-
Admin over 1 year
I'm trying to create an AMP HTML website (see https://www.ampproject.org) But i can't find anywhere how you are supposed to create a responsive hamburger menu ? Javascript is not allowed and there are no AMP Components available for it ?
-
AM Douglas almost 8 yearsThis is how I would have done it as well, especially since the
:focus
pseudo-class doesn't really work on some desktop browsers due to a sort of causality paradox that seems to occur (at least in Chrome).:target
is much more effective and it works well for carousels too, as I've explored here. -
Caio Vertematti over 7 yearsThe live example is not working, when you click the menu item, the menu just closes and doesn't go to the url, the code in the example does the same thing. Did you ever get this code to work correctly?