1

I am using Magento2 and I need to make header sticky for the frontend .how can I make header sticky? When user scroll page then header should be sticky at the top, how we can do this? this code should apply for desktop view only not for a mobile and iPad view. enter image description here

Thanks in advance.

1
  • Do it works in magento 2.3.5 too ? Because it seams there are different folders an structure. Also in back office content- config- header there are a field to add code for the header. Can works if I add there ? Commented Oct 6, 2020 at 19:36

2 Answers 2

5

in header.phtml in your theme add this:

<script type="text/javascript">
require([ "jquery" ], function($){
    $(document).scroll(function () {
        var $window = $(window);
        var windowsize = $window.width();
        var height = $(document).scrollTop();
            if(height  > 150 && windowsize >= 768) {
                $('your header class').addClass('fixed-menu');
            }else{
                $('your header class').removeClass('fixed-menu');
            }
    });
});
</script>
<style type="text/css">
    .fixed-menu{ 
        animation-duration: .45s;
        animation-fill-mode: both;
        animation-name: fadeInDown;
        position: fixed;
        z-index: 500;
        width: 100% ;
        top:0;
        border-bottom: 1px solid #ccccb3;
    }
</style>

hope this will helps you.

5
  • Can you provide exact path ? I add in the header.phtml. but its not working for me
    – Praful
    Commented Nov 16, 2019 at 10:55
  • <your_theme>/Magento_theme/templates/html/header.phtml . If you do not have this file, override it.
    – MichaelHa
    Commented Nov 16, 2019 at 10:57
  • thank you so much . its work for me.
    – Praful
    Commented Nov 16, 2019 at 11:13
  • please accept my answer to helps other dev.
    – MichaelHa
    Commented Nov 16, 2019 at 11:14
  • yes sure i will do..
    – Praful
    Commented Nov 18, 2019 at 9:17
0

You need to add the custom CSS in your stylesheet if its not already there. Here is sample example: https://www.w3schools.com/howto/howto_js_sticky_header.asp Hope this will help? Else comment your link I will share the exact CSS code for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.