JSFiddle - React, Tailwind, and code Playground
by Derek Wood
HTML
<header>
<h1>Example site header</h1>
<button rel='menu-toggle'>
☰
</button>
</header>
<nav class='site-menu'>
<button rel='menu-toggle'>
×
</button>
<a href='#welcome'>Welcome</a>
<a href='#about'>About Me</a>
<a href='#work'>My Work</a>
<a href='#contact'>Contact Me</a>
</nav>
<section id='welcome'>
<h2>Welcome</h2>
</section>
<section id='about'>
<h2>About</h2>
</section>
<section id='work'>
<h2>Work</h2>
</section>
<section id='contact'>
<h2>Contact</h2>
</section>
CSS
* {
box-sizing: border-box;
margin: 0;
}
a {
color: inherit;
}
.site-menu {
background-color: black;
color: white;
padding: 20px;
/* */
display: flex;
flex-direction: column;
align-items: center;
/* */
width: 100%;
max-width: 300px;
/* */
transform: translate(-298px); /* just to show a little */
transition: .2s;
/* */
position: fixed;
top: 0;
left: 0;
/* */
background-color: red;
min-height: 100vh;
}
body.menu-open .site-menu {
transform: translate(0);
background-color: black;
}
header {
/* overly generic - but just for now */
position: sticky;
top: 0;
/* */
background-color: lightgreen;
padding: 20px;
}
section {
/* overly generic - but just for now */
min-height: 110vh;
padding: 20px;
/* padding-top: 120px; */ /* quick and dirty to offset the header */
scroll-margin-top: 100px; /* cool new way */ /* https://caniuse.com/#search=scroll-margin-top */
}
section:nth-of-type(odd) {
/* overly generic - but just for now */
background-color: wheat;
}
JavaScript
function toggleMenu() {
document.body.classList.toggle('menu-open');
// if you put a class on the whole document
// then you'll have more ways to control styles
}
document.addEventListener('click', function(click) { // one listener
if ( click.target.matches('[rel="menu-toggle"]') ) { // many scenarios
toggleMenu();
}
if ( click.target.matches('a') ) {
// click.preventDefault(); // just to stop the links for now...
toggleMenu(); // or you could add the rel to each...
}
})