Animated Sticky Header (Scroll Down): By using the position: sticky
or position: fixed
property, we can easily fix the elements without using Javascript or jQuery plugins.
But creating a fixed header that shrinks On-Scroll with animation couldn’t not possible without a little bit of JavaScript.
The task to build a sticky header that stays fixed top of the page and visible when the user scrolls down the page. Not only this but it also rolls down while the user scrolling the page down or up.
Therefore, our goal to make the header always visible for easy to navigate user experience. Additional, we will apply some nice animation which makes the header content resize into a smaller size.
How to Create Animated Sticky Header On Scroll
Load the important Javascript, jQuery and CSS files into HTML document in the <head> element to start creating an animated fixed header.
<!-- jQuery --> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <script src="js/script.js"></script> <!-- CSS --> <link rel="stylesheet" href="css/style.css">
After that, create the HTML markup for header and add your own links and content. In our index.html file, the markup looks like this:
<div class="header"> <h1>Animated Fixed Header (Scroll Down)</h1> </div> <div class="content">CONTENT GOES HERE</div>
You can easily extend the header part and full fill with navigation links and logo. You can do it like this way but you need to write additional CSS for that.
<div class="header"> <div class="site-title"> <h1>Visit Finland</h1> </div> <nav> <ul> <li><a href="#">Services</a></li> <li><a href="#">Events</a></li> <li><a href="#">Contact</a></li> <ul> </nav> </div>
To make the header sticky, you need to add the following CSS code. If you already define style.css then this code didn’t need to be added.
.header { position: fixed; top: 0; left: 0; width: 100%; background: #cc5350; color:#fff; z-index: 1000; height: 200px; overflow: hidden; -webkit-transition: height 0.3s; -moz-transition: height 0.3s; transition: height 0.3s; text-align:center; line-height:160px; } .header.shrink { height: 100px; line-height:80px; } .header h1 { font-size:30px; font-weight:normal; -webkit-transition: all 0.3s; -moz-transition: all 0.3s; transition: all 0.3s; } .header.shrink h1 { font-size:24px; -webkit-transition: all 0.3s; -moz-transition: all 0.3s; transition: all 0.3s; } .content{ height:2000px; margin-top:200px; /*just to get the page to scroll*/ } article { float: left; padding: 3em 0; }
If you want to add Javascript into existing js file or inline then copy the following code and paste it.
$(function(){ var shrinkHeader = 300; $(window).scroll(function() { var scroll = getCurrentScroll(); if ( scroll >= shrinkHeader ) { $('.header').addClass('shrink'); } else { $('.header').removeClass('shrink'); } }); function getCurrentScroll() { return window.pageYOffset || document.documentElement.scrollTop; } });
By changing the shrinkHeader
value, you can control the browser scroll position.