CSS

CSS3 – Sticky Header on Scroll Example

In this tutorial I’ve setup an example of how to add an animated sticky header to a website using almost pure CSS with just a touch of javascript.

The header becomes ‘sticky’ when the top header bar is scrolled out of view, in the demo this is 40px but can be changed using the LESS variables at the top of the /content/site.less file.

Here it is in action:

(See on Plunker at https://plnkr.co/edit/v8pxS7?p=preview)

HTML for CSS3 Sticky Header

The html is fairly standard with three main sections (divs) for the header, body and footer. The header section is split into two sections (‘header-top’ and ‘header-main’) which are used to apply the styles for the sticky header functionality.

The less.js script is included to compile the LESS stylesheet into CSS on the client side, this is required for the demo to work in plunker but it’s not necessary if you compile the LESS stylesheet on the server or pre compile it using a build tool such as Gulp or Grunt.

<html>
<head>
    <title>CSS3 - Sticky Header on Scroll Example</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
    <link href="content/site.less" rel="stylesheet/less" type="text/css" />

    <script src="//cdnjs.cloudflare.com/ajax/libs/less.js/2.5.3/less.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="js/site.js"></script>
</head>
<body>
    <div id="header">
        <div class="header-top">
            <div class="social-icons">
                <ul class="reset">
                    <li><a href="#" class="fa fa-facebook"></a></li>
                    <li><a href="#" class="fa fa-twitter"></a></li>
                    <li><a href="#" class="fa fa-google-plus"></a></li>
                    <li><a href="#" class="fa fa-github"></a></li>
                    <li><a href="#" class="fa fa-pinterest"></a></li>
                </ul>
            </div>
        </div>
        <div class="header-main">
            <div class="nav">
                <ul class="reset">
                    <li><a href="#" class="current">Home</a></li>
                    <li><a href="#">About</a></li>
                    <li><a href="#">Our Work</a></li>
                    <li><a href="#">Services</a></li>
                    <li><a href="#">Blog</a></li>
                    <li><a href="#">Contact Us</a></li>
                </ul>
            </div>
        </div>
    </div>
    <div id="body">
        <h1>CSS3 - Sticky Header on Scroll Example</h1>
        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam mattis fringilla purus, non sollicitudin lorem. Cras est enim, venenatis non tristique nec, consectetur a nisi. Etiam nec gravida nisi. Morbi massa eros, vulputate sed aliquam a, auctor vestibulum tortor. Sed congue nulla tortor, id aliquet metus elementum vel. Cras fermentum lectus eu purus ultricies, a semper nulla pellentesque. Sed porttitor nibh ut imperdiet bibendum. Nam a neque gravida, consectetur lectus in, bibendum arcu. Aenean eleifend felis eu malesuada sollicitudin.
        </p>
        <p>
            Sed vulputate molestie augue. Suspendisse ac leo vel quam pulvinar ullamcorper ut quis nisl. Donec pretium euismod magna, eu aliquam elit fringilla a. Nulla ornare maximus felis a ullamcorper. Suspendisse potenti. Mauris sit amet nibh mauris. Suspendisse libero justo, lacinia ac purus et, sollicitudin luctus nunc. Quisque finibus ante orci, quis tempus tellus fermentum in. Nulla ac congue dui, eget condimentum nulla. Vivamus at dolor augue.
        </p>
        <p>
            Praesent semper nisi purus, quis vulputate erat dictum et. Sed enim arcu, vulputate sed massa eget, dignissim tempus nisl. Donec pharetra porta vehicula. Ut feugiat, neque eu hendrerit ultricies, augue ex viverra diam, nec suscipit sapien arcu eget massa. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla consequat blandit dapibus. Donec a diam ac leo posuere cursus a non neque. Suspendisse vitae molestie lectus. Pellentesque elit dui, laoreet quis molestie at, tempor ut eros.
        </p>
        <p>
            Proin sit amet metus et velit vestibulum auctor sed eget urna. Fusce eget arcu diam. Maecenas sagittis vehicula pellentesque. Sed et lorem augue. Sed non porttitor lacus. Cras et felis eros. Phasellus enim nibh, sodales vel commodo a, vehicula at sem. Suspendisse cursus, ligula nec efficitur tristique, est nisi fermentum arcu, sit amet efficitur odio sapien a nulla. Praesent vulputate nisl vel mi finibus, eget viverra lectus faucibus. Integer diam risus, molestie in ultricies et, faucibus at urna. In ante libero, aliquet at enim a, consectetur pretium tortor. Etiam vel iaculis velit, vel viverra ligula. Ut venenatis tellus a turpis tristique aliquet. Morbi gravida hendrerit tellus at placerat. Pellentesque nisi tellus, luctus hendrerit nibh in, tincidunt tincidunt dui. Vestibulum mattis iaculis arcu, aliquam aliquam eros rutrum sit amet.
        </p>
        <p>
            Praesent dignissim elementum nunc vel ullamcorper. Curabitur ut auctor diam, vel ullamcorper arcu. Nam non mattis erat. Aliquam erat volutpat. Duis pellentesque, ante ut laoreet convallis, massa urna congue velit, eu eleifend mi orci vitae mauris. Curabitur rutrum dui non fermentum consectetur. Sed est arcu, ornare quis auctor et, suscipit quis mi. Sed diam ex, interdum non risus sed, aliquam ullamcorper arcu. Proin ut lorem in enim auctor malesuada.
        </p>
        <p>
            Maecenas scelerisque sodales sodales. Suspendisse nec arcu et mi aliquam pulvinar. Morbi purus nisl, commodo eget tristique sit amet, commodo vitae dolor. Maecenas vel ultricies dolor. Morbi lacinia, nunc maximus faucibus pharetra, nibh nulla finibus magna, eu interdum magna metus mollis tortor. Morbi ex ex, dignissim et ex a, euismod vestibulum libero. Integer orci felis, aliquet ullamcorper euismod et, gravida sit amet elit. Nunc tristique lacus in neque mollis varius. In dapibus erat eros, et pellentesque odio lacinia bibendum. Vivamus dui nulla, accumsan a justo id, scelerisque condimentum odio. Curabitur euismod volutpat nunc.
        </p>
        <p>
            Suspendisse eu enim mollis, tempus eros nec, consectetur est. Pellentesque semper finibus tristique. Proin sit amet gravida mi, mattis dapibus dolor. Phasellus cursus malesuada tortor, vel lobortis felis dignissim maximus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Donec dapibus sem a luctus sodales. Sed placerat in urna ac imperdiet. Phasellus quis sollicitudin augue. Nullam tortor nulla, aliquam quis blandit non, tempus non lorem. Vivamus nisl justo, dignissim et consequat sed, maximus vitae erat.
        </p>
        <p>
            Duis dignissim quam velit. Nulla suscipit at lacus eget placerat. Maecenas sed sem id augue lacinia efficitur. Integer risus ipsum, maximus in tellus eget, iaculis iaculis augue. Aliquam tincidunt nisi sit amet laoreet cursus. Nunc egestas tellus euismod, convallis erat ut, dapibus dui. Donec dapibus urna et pellentesque accumsan. Cras et tincidunt mi, a eleifend leo. Morbi pretium ex vel lacus porta tincidunt. Sed varius aliquam placerat. Maecenas condimentum, dui vitae volutpat lacinia, mauris mauris vestibulum mauris, vitae ultrices mi dui quis enim. Etiam lorem libero, blandit et maximus at, aliquet dignissim erat. Etiam eleifend tempor ipsum eu dignissim. Donec fermentum sapien non urna venenatis, ut hendrerit nisl imperdiet.
        </p>
        <p>
            Aenean libero quam, lobortis at neque sodales, imperdiet ornare ante. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec ut fermentum nulla. Nunc scelerisque massa et gravida efficitur. Etiam sed blandit enim. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam scelerisque dignissim tellus ut ornare. Nulla sit amet magna ac felis finibus tempus non non massa. Sed a venenatis leo, ut mollis est. Curabitur mollis felis et lacus vestibulum, eu rhoncus ligula accumsan. Nulla eleifend nisl ut ultricies imperdiet. Nam scelerisque metus eget aliquam gravida. Donec blandit orci quis est fermentum suscipit. Ut dictum metus ut urna pretium cursus. Proin aliquet placerat augue ac bibendum.
        </p>
    </div>
    <div id="footer">
        <p>
            <a href="https://wpproonline.com/css3-sticky-header-on-scroll/" target="_top" rel="noopener noreferrer">CSS3 - Sticky Header on Scroll Example</a>
        </p>
        <p>
            <a href="https://wpproonline.com/" target="_top" rel="noopener noreferrer">WP Pro Online</a>
        </p>
    </div>
</body>
</html>

LESS / CSS Styles for CSS3 Sticky Header

The LESS styles are split up into sections to make them easier to follow, I’ve also created variables for the sticky header values at the top of the file, you can edit these variables to change the size of the header sections.

There’s also a handful of styles that are purely for look and feel and aren’t related to the sticky header functionality, I left them in so the demo looks better and is a bit more of a real world example.

/* VARIABLES
--------------------------------------------*/@header-top-height: 40px;      /* height of the top section of the header */@header-main-height: 100px;    /* default height of the main section of the header */@header-sticky-height: 60px;   /* height of the header when it's sticky */
/* GLOBAL DEFAULTS
--------------------------------------------*/body {
    padding: 0;
    margin: 0;
    font-family: Arial;
}

a {
    transition: color 0.3s;
}

/* GENERAL CLASSES
------------------------------------------*/ul.reset {
    margin: 0;
    padding: 0;

    > li {
        list-style: none;
    }
}

/* HEADER SECTION
--------------------------------------------*/#header {
    position:absolute;
    top:0;
    width:100%;

    .header-top {
        height: @header-top-height;
        line-height: @header-top-height;
        background: #1b2327;
        color: #b0bec5;

        .social-icons {
            float: right;

            ul {
                li {
                    float: left;
                    margin-left: 5px;
                    font-size: 20px;

                    a {
                        color: inherit;
                        text-decoration: none;
                        display: inline-block;
                        width: 40px;
                        text-align: center;
                        line-height: 40px;

                        &:hover {
                            color: #fff;
                        }
                    }
                }
            }
        }
    }

    .header-main {
        height: @header-main-height;
        line-height: @header-main-height;
        background: #263238;
        padding: 0 20px;
        box-sizing: border-box;
        
        /* animate the transition between normal header and sticky header */        transition: height .3s, line-height .3s;

        .nav {
            float: left;

            ul {
                li {
                    float: left;

                    a {
                        color: #cfd8dc;
                        text-decoration: none;
                        text-transform: uppercase;
                        display: inline-block;
                        padding: 0 10px;

                        &.current {
                            color: #80cbc4;
                        }

                        &:hover {
                            color: #fff;
                        }
                    }
                }
            }
        }
    }
}

/* BODY SECTION
--------------------------------------------*/#body {
    padding-top: @header-top-height + @header-main-height;
    padding-left: 15px;
    padding-right: 15px;
    background: #eee;
    transition: padding-top .3s;
}

/* FOOTER SECTION
--------------------------------------------*/#footer {
    background: #1b2327;
    padding: 20px;
    text-align: center;
    
    a {
        color: #b0bec5;
        text-decoration: none;

        &:hover {
            color: #fff;
        }
    }
}

/* STICKY HEADER STYLES
--------------------------------------------*/body.sticky-header {
    #header {
        .header-main {
            height: @header-sticky-height;
            line-height: @header-sticky-height;
            position: fixed;
            top:0;
            width: 100%;
        }
    }

    #body {
        padding-top: @header-top-height + @header-sticky-height;
    }
}

Javascript / jQuery for CSS3 Sticky Header

Javascript is used to toggle the ‘sticky-header’ class on the body tag when the header top section is scrolled in and out of view using the jQuery .scrollTop() function. The ‘sticky-header’ class is used in the stylesheet above to switch on and off the sticky header functionality.

$(window).scroll(function () {
    // add 'sticky-header' class to the body tag when the header top is scrolled out of view
    $('body').toggleClass('sticky-header', $(this).scrollTop() > $('.header-top').height());
});

Recent Posts

Unlocking the Secrets of JSON.stringify(): More Than Meets the Eye

JSON (JavaScript Object Notation) is a lightweight data-interchange format widely used in web development. At…

2 months ago

How to Handle AJAX GET/POST Requests in WordPress

AJAX (Asynchronous JavaScript and XML) is a powerful technique used in modern web development that…

3 months ago

Page Speed Optimization: Post-Optimization Dos and Don’ts

Introduction After successfully optimizing your website for speed, it's essential to maintain and build upon…

3 months ago

Ultimate Guide to Securing WordPress Folders: Protect Your Site from Unauthorized Access

Securing your WordPress folders is crucial to safeguarding your website from unauthorized access and potential…

4 months ago

HTML CSS PHP File Upload With Circle Progress Bar

Creating a file upload feature with a circular progress bar involves multiple steps. You'll need…

4 months ago

Using WP Rocket with AWS CloudFront CDN

Integrating WP Rocket with AWS CloudFront CDN helps to optimize and deliver your website content…

4 months ago