Make Sticky Header in Magento 2 – Solving JavaScript and CSS Issues

cssjavascriptmagento2magento2.2.3

I'm following the answer in this topic to keep header sticky. So far I've created vendor/theme/web/js/sticky.js with the following content:

require([ "jquery" ], function($) {
    $(window).scroll(function() {
        if ($(window).scrollTop() > $('#header').offset().top && !($('#header').hasClass('sticky'))) {
            $('#header-2').addClass('sticky');
        } else if ($(window).scrollTop() == 0) {
            $('#header').removeClass('sticky');
        }
    });
});

and called this file inside vendor/theme/Magento_Theme/layout/default_head_blocks.xml

<link src="js/sticky.js"/>

Second part of this answer says:

"add some css to this sticky class like this:"

#header.sticky {
    background: #fff none repeat scroll 0 0;
    border-bottom: 4px solid #325052;
    margin: 0 auto;
    max-width: 100%;
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 99;
}

How can I implement this part? I've tried creating a css/sticky.css file with the code above and link it on default_head_blocks.xml ( <css src="css/sticky.css"/> ), but it's not working.

Best Answer

You can use default M2 Sticky

define([
    'jquery', 
    'mage/mage', 
    'domReady!'
], function ($) {
    $('#header').mage('sticky', {
        container: '#maincontent',
        spacingTop: 0
    });
});

And CSS

#header {
  position: relative;
}
Related Topic