News

Unleash HTML, CSS and JS to create an on-scroll menu

Code a slide menu that repositions when the user scrolls.

Screen-shot-2015-01-22-at-12.47.40

Screen shot 2015-01-22 at 12.47.40

inspiration: niceandserious.com

DOWNLOAD TUTORIAL FILES

Create the base HTML

Make a start by creating the header in your HTML page. Your content can be added later, whatever that content will be, but bear in mind that you won’t see any results from the functionality until your page is large enough to scroll. A holding image or similar dummy content may be a good idea.

001 <header>
002 <div>
003 <nav>
004 <ul></ul>
005 </nav>
006 </div>
007 </header>

Add links

Add the <li> elements inside your <ul>. It would be handy to know what your navigation elements are going to be in advance as we will eventually want to give the entire list a set width. Should you need to add links later though, it can be adapted. Now we can start adding some CSS.

001 <ul>
002 <li><a href="#">This Thing</a></li>
003 <li><a href="#">That Thing</a></li>
004 <li><a href="#">Another Thing</a></    li>
005 <li><a href="#">Something</a></li>
006 <li><a href="#">Nothing</a></li>
007 </ul>

Initial CSS

Our body will need to be padded at the top to allow room for the header. The padding and height of the header is 60px. Positioning is going to play a massive part in this function, beginning with a fixed position for the header. We can also add some basic styling for the <ul> and <li> elements. Style the <a> links as you wish.

001 body {padding-top: 60px;}
002 header {position:fixed;         width:100%; top:0; background:rg    ba(250,250,250,0.8);
003 height:60px;}
004 ul {padding:0;}
005 ul li {display: inline-block;     padding: 5px 15px;}

Positioned elements

Next up we’ll add some details to the container, including the width and margins to keep it central, which of course only works once we’ve declared a width for our <nav> element. We also need to give the container a relative position so that we can control the absolutely positioned child nav element within it.

001 .container {width: 1200px; margin:     auto; padding: 0 15px; position:     relative;}
002 nav {width:650px;position:absolute;}

Create nav classes

Now we need to create the two classes that our JavaScript will add and remove to the nav element to create the sliding effect. Positioning declarations allow us to now use numerical declarations so that we can utilise animated transitions between the two nav element classes. Don’t forget to add vendor prefixes to both the transition and transform declarations.

001 .center {margin-left: auto; margin-    right: auto; left: 0; right: 0;     transition: all 0.7s ease;}
002 .right {margin-left: auto; margin-    right: auto; left: 0; right: 50%;     transform: translateX(100%); transition: all 0.7s ease;}
003
×