简体   繁体   中英

Using position: fixed for navigation not working as expected

I've created a JSFiddle to show my webpage structure HTML and CSS.

http://jsfiddle.net/du7NN/

I've been trying to build a page where when scrolling the navigation sticks to the top of the page while the rest of the reader disappears and rest of the page scrolls but when I add position:fixed on the .nav class It stops the background-color from spanning the whole width of the page and overrides my text-align: center. Here is the rest of my CSS:

.header {
    text-align: center;
}

.nav {
    position: fixed;
}

.nav ul {
    padding: 0;
    margin: 0;e
    list-style: none;
    /* display: block; */
    background-color: #eee;
}

.nav li {
    display: inline-block;
    padding: 0 10px;
}

I've come across a few examples of how to fix this, but finding it hard to understand how to apply it to my issue.

What do you guys think?

Without getting very detailed, here is a codepen for you . You need to add the fixed positioning and background to the parent element, .header, not the child elements.

Here is some possible js for the other activity:

jQuery(document).ready(function($) {
    var s = $("nav");
    var pos = s.position();                    
    $(window).scroll(function() {
        var windowpos = $(window).scrollTop();
        if (windowpos >= pos.top) {
            s.addClass("stick");
            $('#rewrap').addClass("bump");
        } else {
            s.removeClass("stick"); 
            $('#rewrap').removeClass("bump");
        }
    });
});

Absolute or fixed positioned element have their automatically calculated width calculated as “shrink-to-fit”, meaning they are only as wide as their content requires.

So give your navigation an explicit width, or position it from both “sides”, using left:0; right:0 left:0; right:0 .

(And your text-align:center was of course not “overridden”, but just had no visible effect – because the element was only as wide as its content required, and then there is nothing more to “center” …)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM