How it works
This implementation uses a hidden checkbox together with the CSS sibling selector '~' to change the formatting on a number of elements at once. The checked
pseudo selector is used to effect these changes, even though the checkbox it applies to is not visible on screen.
Specifically, the rules
#hamburger input:checked ~ ul {
transform:translate(0,0);
opacity:1;
}
#hamburger input:checked ~ div.closedHamburger {
opacity:0;
}
#hamburger input:checked ~ div.openHamburger {
opacity:1;
}
operate on the siblings of the input element whenever that element is checked. This allows us to change the opacity of the open and closed hamburger buttons, and to slide the manu in and out of the page.
A small amount of HTML contains the required elements, with the CSS implenting the functionality.
The HTML
<nav role="navigation">
<!-- All the magic takes place inside this container div -->
<div id="hamburger">
<!-- An invisible check box -->
<input type="checkbox" >
<!-- Two symbols for hamburger open and closed. These exist in the same
place on the page, but one is opaque while the other is transparent -->
<div class="closedHamburger">☰</div>
<div class="openHamburger">✖</div>
<!-- Here's our menu -->
<ul>
<li><a href="#">Home</li>
<li><a href="#">Products</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
</nav>
The CSS
<style>
body {
font-family: "Segoe UI", Arial,sans-serif;
font-size:20pt;
}
#hamburger {
position:relative;
}
#hamburger div {
font-size:40px;
display:block;
position:absolute;
top:0;
left:0;
}
/* Format the check box, set opacity to 0 to hide it, and place it over the hamburger symbol */
#hamburger input {
display:block;
position:absolute;
top: 0;
left: 0;
width:40px;
height:40px;
opacity:0;
z-index:4;
cursor:pointer;
}
/* Formatting for closed and open hamburger symbols */
#hamburger div.closedHamburger {
opacity:1;
z-index:3;
transition: opacity 0.5s;
margin-left:6px;
margin-top:-5px;
color:black;
}
#hamburger div.openHamburger {
opacity:0;
z-index:3;
transition: opacity 0.5s;
margin-left:6px;
margin-top:-5px;
color:white;
}
/* Some formatting for the menu */
#hamburger ul {
color:white;
background-color:navy;
transition: transform 1s, opacity 1s;
width:250px;
border-radius:20px;
margin-top:0;
transform:translate(0,-100%);
opacity:0;
position:absolute;
z-index: 2;
padding:5px 40px;
}
#hamburger li {
margin-left:20px;
list-style:none;
}
#hamburger a {
color: white;
text-decoration: none;
}
#hamburger a:hover {
color:grey;
}
/* When the invisible checkbox is checked, these rules use the sibling selector
to change the opacity and position of the hamburger buttons and the menu
*/
#hamburger input:checked ~ ul {
transform:translate(0,0);
opacity:1;
}
#hamburger input:checked ~ div.closedHamburger {
opacity:0;
}
#hamburger input:checked ~ div.openHamburger {
opacity:1;
}
</style>
The downlod includes a single page demo including all the CSS and HTML.
Questions or comments? Contact me!