How to pin a "horizontal menu" to the top of the window when scrolling the page?

Asked

Viewed 76,380 times

45

I have a layout with a horizontal navigation bar at the top of the site, it is with margin-top:100px, when scrolling the page the menu should be fixed at the top of the window but with margin-top:0.

What’s the best way to accomplish this?

5 answers

34


You need to control when your menu reaches the top of the window and at that time change the menu position to fixed.

Thus $('#meuMenu').offset().top will give you the distance to the top.

When the distance is <= to the scroll value of the page, then you can add a CSS class that forces the fixed position:

.fixar {
    position:fixed;
    margin-top: 0px !important;
}

So javascript/jquery can be:

var offset = $('#meuMenu').offset().top;
var $meuMenu = $('#meuMenu'); // guardar o elemento na memoria para melhorar performance
$(document).on('scroll', function () {
    if (offset <= $(window).scrollTop()) {
        $meuMenu.addClass('fixar');
    } else {
        $meuMenu.removeClass('fixar');
    }
});

Demo

5

Not if that’s what you want, follow an example:

HTML of the Page:

<div class="nav-container">
<div class="nav">
    <ul>
        <li><a href="">Home</a></li>
        <li><a href="">CSS</a></li>
        <li><a href="">PHP</a></li>
        <li><a href="">SEO</a></li>
        <li><a href="">jQuery</a></li>
        <li><a href="">Wordpress</a></li>
        <li><a href="">Services</a></li>
    </ul>
    <div class="clear"></div> /*clear floating div*/
</div>
</div>

To make the horizontal menu, you need the following CSS:

.nav-container{ background: url('images/nav_bg.jpg') repeat-x 0 0;}
    .f-nav{ z-index: 9999; position: fixed; left: 0; top: 0; width: 100%;} /* this make our menu fixed top */
    
.nav { height: 42px;}
    .nav ul { list-style: none; }
    .nav ul li{float: left; margin-top: 6px; padding: 6px; border-right: 1px solid #ACACAC;}
    .nav ul li:first-child{ padding-left: 0;}
    .nav ul li a { }
    .nav ul li a:hover{ text-decoration: underline;}

And a little javascript code:

jQuery("document").ready(function($){
    
    var nav = $('.nav-container');
    
    $(window).scroll(function () {
        if ($(this).scrollTop() > 136) {
            nav.addClass("f-nav");
        } else {
            nav.removeClass("f-nav");
        }
    });

});

Source: http://www.sutanaryan.com/how-to-create-fixed-menu-when-scrolling-page-with-css-and-jquery/

3

You can check like this:

$(window).on('scroll', function() {

    if($(this).scrollTop() >= $('.menu').offset().top) {

        $('.menu:not(.fixed)').addClass('fixed');

    } else $('.menu.fixed').removeClass('fixed');

});

In the CSS class "Fixed" you can change the positioning type and remove the margin.

1

In fact, with HTML 5 and CSS 3 you don’t have to do any JQUERY or anything like that. Twitter Bootstrap has a navbar of this style. just use the expression "navbar-Fixed-top" in the object

0

It can be achieved only with CSS assigning the value sticky to the property position:

#menu {
    position: sticky;
    top: 0;
}

The compatibility of the feature is very broad, but it seems that it does not fuinciona no IE.

Link about Sticky value in CSS position property

Link to Compatibility between the browsers


Example:

body {
padding: 0;
margin: 0;
}

p {
padding: 0 10px;
text-align: justify;
}

#menu {
position: sticky;
top: 0;
margin-top: 100px;
padding: 20px;
background-color: #000;
color: #fff;
}
<html>

<body>

<div id="menu">MENU</div>

<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam imperdiet risus vel nulla tempus congue. Donec tincidunt, risus ac convallis tristique, nulla quam tempor turpis, et convallis ipsum felis a est. Donec iaculis at urna et egestas. Nunc purus erat, venenatis a nunc at, condimentum hendrerit lectus. Nunc aliquam purus ut massa consectetur, interdum elementum nisi aliquet. Sed rhoncus varius sapien, hendrerit tempor erat accumsan quis. Nulla tortor leo, tincidunt ac fringilla quis, malesuada non augue. Curabitur non erat cursus metus cursus hendrerit et eu tellus. Nunc mollis, nisl non porta porta, urna tellus malesuada nunc, sollicitudin semper nulla justo sed neque. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed ultrices accumsan hendrerit. Aliquam luctus rutrum cursus. Maecenas ultrices nisi eu est volutpat, eu posuere felis volutpat. Nullam et leo euismod, volutpat massa eu, commodo dolor. Nunc ut blandit ex, porta consectetur purus. Nunc sit amet dolor et elit convallis convallis vitae non metus.</p>

<p>Aliquam eu libero turpis. Ut non magna at libero tincidunt lacinia et vel eros. Aenean eget nibh nec purus fringilla placerat vitae ut nisi. Praesent quis consequat urna. Vivamus porta, ante posuere finibus dignissim, lacus ante fringilla enim, vel lacinia felis nisl at elit. Suspendisse sodales sollicitudin suscipit. Etiam commodo quam nisi, quis dapibus nisl hendrerit sed. Vestibulum suscipit ut felis non vulputate.</p>

<p>Donec tempor urna quis nunc pellentesque maximus. Sed elit dui, vestibulum rutrum consequat a, viverra a leo. Vivamus eget nibh semper, suscipit eros vel, malesuada libero. Duis laoreet tempus neque, sit amet maximus odio consectetur vitae. Duis vestibulum faucibus velit eget pharetra. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Integer ultrices interdum ex, semper maximus turpis condimentum ut. Maecenas libero mi, bibendum vel eleifend vel, varius at neque. Praesent varius risus et diam elementum, at commodo purus fermentum. Nam luctus tempor cursus.</p>

<p>Donec rhoncus eros ipsum, ut lobortis quam tristique eu. Aliquam rhoncus, odio quis suscipit condimentum, massa ante porta dui, vel sodales sem augue quis augue. Nam maximus placerat velit in rhoncus. Nulla facilisi. Suspendisse eget mattis tellus. Nullam molestie tortor porttitor urna pretium, vestibulum consectetur odio molestie. Nunc ligula mauris, semper sit amet convallis ut, placerat lacinia nisi. Nunc eget lacinia dolor. Quisque placerat tellus mi, id pretium velit posuere efficitur. Nullam vitae mauris ac justo tempus lacinia id sed mauris.</p>

<p>Mauris maximus quis tortor ac semper. Proin vestibulum sed elit vel sagittis. Pellentesque sed turpis nec quam pellentesque pharetra. Suspendisse ac consectetur elit. Ut erat dolor, porttitor at tempus in, fermentum id risus. Suspendisse urna massa, blandit sed interdum nec, dapibus at nisi. Nullam eu dui ut elit dapibus venenatis eu ac magna. Nunc vehicula eget est ut sollicitudin. Suspendisse id nulla metus. Aenean suscipit luctus metus, at convallis dolor tincidunt eget.
</p>

</body>

</html>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.