简体   繁体   中英

Fixed top menu scrolling along with content

I'm attempting to make a fixed top menu. On a viewport > 1170px (which is my minimum page viewport here), everything is ok. On viewport less than 1170px, main content of the page is horizontally scrollable (ok), but #main-menu is displayed only up to current window height, so the last items are hidden.

Is is possible to make this menu fixed and to act like a part of the scrollable content?

The site will be not responsive.

HTML:

<nav id="main-menu">
    <div class="container">
        <ul class="nav">
            <li id="item1"><a href="#">Menu item 1</a></li>
            <li id="item2"><a href="#">Menu item 2</a></li>
            <li id="item3"><a href="#">Menu item 3</a></li>
            <li id="item4"><a href="#">Menu item 4</a></li>
            <li id="item5"><a href="#">Menu item 5</a></li>
        </ul>
    </div>
</nav>

<div id="content">
    <div class="container">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce bibendum odio et interdum pretium.</p>
    </div>
</div>

CSS

body {
  background-color: #000;
  color: #fff;
  font-size: 17px;
  min-width: 1170px;
}
.container {
  width: 1170px;
}
#main-menu {
  position: fixed;
  height: 68px;
  width: 100%;
  display: block;
  top: 0px;
  z-index: 500;
}

#content {
  position: relative;
  top: 150px;
}

DEMO: http://jsfiddle.net/zyqkrwtk/1/

I know it is partially solvable by setting overflow-x: auto to menu, but there will be extra scrollbar, which is not desirable.

EDIT: Sorry, I forgot to mention important thing - the page content is actually very long (it will be one-page microsite), so the fixed position is therefore desirable. Updated demo - http://jsfiddle.net/fvgf2mj6

You have unnecessary uses of the CSS rule position .

I fixed your code here http://jsfiddle.net/nuc4s6h9/ Basically I removed the style for #content element and the position:relative for #main-menu element. Out of the box this 2 elements have display:block which made them render one below the other.

Let me know if that is what you wanted for.

Ok, so I'm coming back with my solution! I have inspired in this similar question Centering a fixed element, but scroll it horizontally

Basically everything I had to change was

#main-menu {
position: absolute
...

and add this little jQuery code to set menu position and width when user scrolls/resizes window:

var alignMenu = function() {
    $('#main-menu').css({
        'top': $('body').scrollTop(),
        'width': $('#vystuduj-to').width()
    })
}

$(window).scroll(function(){ alignMenu() });
$(window).resize(function(){ alignMenu() });

DEMO: http://jsfiddle.net/LorLe7jx/

Thanks to everybody for pointing out to right direction!

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