Horizontally centred CSS dropdown menu (steps)
by Matt Hinchliffe
HTML
<div class="demo-controls">
<button type="button" id="prev">Previous step</button>
<button type="button" id="next">Next step</button>
</div>
<div class="demo-canvas">
<div class="nav-bar">
<div class="root">
<a href="#" class="toggle">Toggle</a>
<div class="panel">
<div class="wrapper"></div>
</div>
</div>
</div>
</div>
CSS
/* Demo housekeeping */
body {
font: normal 16px/1.5 Arial, sans-serif;
}
.demo-controls {
margin: 0 0 10px;
text-align: center;
}
/* Demo setup */
.nav-bar {
text-align: center;
}
.root {
/* Create a new containing block */
position: relative;
/* No red should be visible */
background: rgba(255, 0, 0, .5);
}
.toggle {
/* Prettify the toggle */
padding: 5px 10px;
text-decoration: none;
color: white;
/* No blue should be visible */
background: rgba(0, 0, 255, .5);
}
.panel {
/* Yellow */
background: rgba(255, 255, 0, .25);
border: 1px solid rgba(255, 255, 0, .5);
}
.wrapper {
/* Green */
background: rgba(0, 255, 0, .5);
}
/* Step 1: Shrink wrap the .toggle element */
.step-1 .root {
display: inline-block;
}
.step-1 .toggle {
display: block;
}
/* Step 2: Position the .panel element */
.step-2 .panel {
position: absolute;
/* Relative to the .root container */
left: 50%;
}
.step-2 .wrapper {
width: 200px;
height: 100px;
}
/* Step 3: Shift the wrapper back into position */
.step-3 .wrapper {
/* Relative to the width of .panel */
margin-left: -50%;
}
JavaScript
var steps = 3;
var current = 0;
var next = document.getElementById('next');
var prev = document.getElementById('prev');
var canvas = document.querySelector('.demo-canvas');
next.onclick = function() {
if (current < steps) {
step(current + 1);
}
};
prev.onclick = function() {
if (current > 0) {
step(current - 1);
}
};
function step(to) {
if (to > current) {
canvas.className+= ' step-' + to + ' ';
}
else {
canvas.className = canvas.className.replace(' step-' + current + ' ', '');
}
next.disabled = (to >= steps);
prev.disabled = (to <= 0);
current = to;
}
step(0);