how do I keep a nav bar at the top of the page?
Asked Answered
S

9

16

I'm trying to make my nav bar stay at the top of the page like on forbes.com

I know I could do

nav
{
   position: fixed;
   top: 0;
}

but the nav bar isn't at the top of the page, it comes after the logo... When you scroll down however, I want the nav bar to stick to the top of the screen..

This is my site

Saponify answered 18/1, 2013 at 1:11 Comment(6)
They are using javascript/jQuery to handle this - you can see the "container large" class has a style that switches when it hits the top of the page. When it hits the top, it becomes fixed, otherwise it's relative --- Are you willing to use Jquery?Positron
I'm willing to use jquery even though I've not really ever coded it - I'm pretty good with CSS and HTML? Will it be simple enough? What would the code look like?Saponify
The basic premise is this: get the height of the header (above the nav) get the position of the window (the entire document). When the position of the window is greater than the position of the header height, give the nav a new style of position:fixed. Unfortunately, I don't have enough time to actually write it.Positron
Thanks for the help - I'll hopefully be able to figure this one :DSaponify
it can be done in pure css. looks like you solution works well in firefox and not ie. In ie it is not inheriting the backgroundPhilodendron
If you don't mind using a framework, take a look at Twitters Bootstrap. It can do that and many other really cool things with very little developer effort.Hekking
B
13

the solution is easy, keep your css while adding px

nav
{
   position: fixed;
   top: 0px;
}
Breeder answered 25/7, 2013 at 17:28 Comment(0)
T
7

You could try it in JQuery like this:

HTML:

<div id="wrapper">

    <header>
        <h1>Floater Navigation</h1>
    </header>

    <nav>
        <p>Navigation Content</p>
    </nav>

    <div id="content">
            <p>Lorem Ipsum.</p>
    </div>
</div>

CSS:

#wrapper {
    width:940px;
    margin: 0 auto;
}

header {
    text-align:center;
    padding:70px 0;
}

nav {
    background: #000000;
    height: 60px;
    width: 960px;
    margin-left: -10px;
    line-height:50px;
    position: relative;
}

#content {
    background: #fff;
    height: 1500px; /* presetting the height */
    box-shadow: 0 0 5px rgba(0,0,0,0.3);
}

.fixed {
    position:fixed;
}

JQuery:

$(document).ready(function() {

    // Calculate the height of <header>
    // Use outerHeight() instead of height() if have padding
    var aboveHeight = $('header').outerHeight();

    // when scroll
    $(window).scroll(function(){

        // if scrolled down more than the header’s height
        if ($(window).scrollTop() > aboveHeight){

            // if yes, add “fixed” class to the <nav>
            // add padding top to the #content 
            // (value is same as the height of the nav)
            $('nav').addClass('fixed').css('top','0').next().css('padding-top','60px');

        } else {

            // when scroll up or less than aboveHeight,
            // remove the “fixed” class, and the padding-top
            $('nav').removeClass('fixed').next().css('padding-top','0');
        }
    });
});

source: http://www.jay-han.com/2011/11/10/simple-smart-sticky-navigation-bar-with-jquery/

Tachyphylaxis answered 1/3, 2013 at 6:1 Comment(1)
Thanks, works fine. easy to integrate and to understand. But i only used tag ´nav´ and two styles for ´nav´ and ´.fixed´. The rest of element, what they are used to?Boll
A
2

Here is a way to do it without JQuery. It works by setting a scroll listener to the window, and switching the class of the nav bar when the scroll reaches the right position.

var body = document.getElementsByTagName("body")[0];
var navigation = document.getElementById("navigation");

window.addEventListener("scroll", function(evt) {
  if (body.scrollTop > navigation.getBoundingClientRect().bottom) {
    // when the scroll's y is bigger than the nav's y set class to fixednav
    navigation.className = "fixednav"
  } else { // Overwise set the class to staticnav
    navigation.className = "staticnav"
  }
});
h1 {
  margin: 0;
  padding: 10px;
}
body {
  margin: 0px;
  background-color: white;
}
p {
  margin: 10px;
}
.fixednav {
  position: fixed;
  top: 0;
  left: 0;
}
.staticnav {
  position: static;
}
#navigation {
  background-color: blue;
  padding: 10px;
  width: 100%;
}
#navigation a {
  padding: 10px;
  color: white;
  text-decoration: none;
}
<h1>
Hello world
</h1>
<nav id="navigation" class="staticnav"><a href="#">Home</a>  <a href="#">About</a>
</nav>
<!-- We initialize the nav with static condition -->
<p>
  Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text.
  Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text.
  Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text.
  Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text.
  Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text.
  Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text.
  Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text.
  Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text.
  Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text.
  Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text.
</p>
Aircrew answered 7/6, 2016 at 21:26 Comment(0)
E
2

You can use:

nav
{
   position: fixed;
   top: 0;
   left: 0;
}

See this complete example example:

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: sans-serif;
}

#header {
    width: 100%;
    height: 90vh;
    text-align: center;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    padding: 60px 12px;
}

header nav {
    width: 100%;
    height: 10vh;
    background-color: #262534;
    display: grid;
    align-items: center;
    border-bottom: 4px solid #F9690E;
    position: fixed;
    top: 0;
    left: 0;
}

header .nav-item {
    display: inline;
    margin: 0 8px;
}

header .nav-item:first-of-type {
    margin-left: 48px;
}

header .nav-item a {
    color: white;
    text-decoration: none;
    font-size: 16px;
}

header .nav-item a:hover {
    text-decoration: underline;
}

header #more-drop-down-menu a:last-of-type:hover {
    text-decoration: none;
}

header .nav-item a.active {
    text-decoration: underline;
    color: #F9690E;
}

/** menu**/
menu{
  margin-top:14vh;
  text-align: center;
}
menu p{
  font-size: 14px;
  line-height:125%;
  padding: 25px;
}
<header>
         
        <!-- Start Nav -->
        <nav>
            <ul>
                <li class="nav-item"><a href="#Home" class="active">Home</a></li>
                <li class="nav-item"><a href="#About">About</a></li>
                <li class="nav-item"><a href="#Contact">Contact</a></li>
                <!-- END Drop Down Menu -->

            </ul>
        </nav>
        <!-- End Nav -->   
    </header>
 <menu>
 <h1> Example of fixed nav</h1>
     <p>
         Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cumque exercitationem ipsa quisquam sunt ex blanditiis iure vero molestias impedit recusandae eius quasi unde assumenda molestiae, dolorem illum, aliquid aut neque?
         Error aut voluptatum molestias ad quidem odio labore eaque veniam fugiat earum, aliquid incidunt beatae nam pariatur minus voluptates atque suscipit cupiditate et! Tenetur eveniet delectus aspernatur? Perferendis, modi similique.
         Debitis eaque suscipit tenetur, laboriosam perferendis possimus voluptas expedita labore aspernatur. Nobis cum vel quae voluptates pariatur architecto quas labore assumenda ipsam sint tenetur, nisi in non alias quisquam atque.
         Animi, exercitationem ullam laudantium dolores praesentium distinctio illo, fugiat iusto soluta quibusdam eius? Quaerat reiciendis voluptatum voluptatibus porro saepe blanditiis nam iure odio soluta, cum ipsam, suscipit molestiae natus eius!
         Quasi, quae harum? Fuga facere facilis, cumque veniam voluptatum itaque aspernatur natus ratione nesciunt dolores qui, iste ullam dolorem totam accusantium officiis nisi hic esse reiciendis molestias. Unde, inventore fugiat?
         Corrupti similique consequatur provident aliquam voluptates minima modi voluptatibus exercitationem magni, consectetur delectus? Rerum quo cumque dolorem voluptatibus tempora, nesciunt laboriosam eum assumenda deserunt error ullam asperiores velit suscipit corrupti!
         Perspiciatis architecto illo quis dolore necessitatibus ad accusantium voluptatem esse ducimus! Modi facilis consequuntur mollitia asperiores praesentium. Tempora vero quod aliquam, alias quis, nisi cumque totam sed odit, hic suscipit.
         Aut molestias minus accusantium, cumque, aspernatur quia aliquam accusamus nostrum saepe, eius vero velit. Labore a deserunt voluptate illo, eum eos, ad saepe, eius temporibus quis eaque ea reiciendis soluta!
     </p>
 </menu>
Eluviation answered 27/11, 2019 at 16:3 Comment(0)
G
1

This is how the navigation-bar sticks to the top after scrolling past it.

.affix {
	top: 0px;
	margin: 0px 20px;
}
.affix + .container {
	padding: 5px;
}
<nav class="navbar navbar-default" data-spy="affix" data-offset-top="50">
...
</nav>

"navbar" creates a block on it's own, so all you've to do is mention only the margin in your css file .navbar { margin: 0px auto; /*You can set your own margin for top-bottom & right-left respectively*/ z-index: 1; } The z-index sets priority to that particular element, so that other elements do not scroll over it. If z-index has a positive value, then it has the highest priority otherwise lowest priority(for negative values). I hope this is helpful.

Galer answered 21/9, 2017 at 17:15 Comment(0)
C
1
nav {
    position: sticky;
    top: 0;
}
Conlee answered 13/12, 2019 at 17:27 Comment(1)
Please provide more details about your answer.Chiang
T
0

Here is the method I tried

.nav{
    position: sticky;
    top: 0;
    width: 100%;
}
Tol answered 8/6, 2022 at 15:52 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Zechariah
S
-1

Use position absolute and set the top value to the number of pixels you want the Nav bar to be from the top of the browser.

Stertor answered 18/1, 2013 at 2:55 Comment(6)
Isn't that what you want? To control how far the bar is from the top of the screen? It works for me and I use it all the time.Stertor
Ok so Forbes uses position fixed, the problem is that wont work on tablets and phones. That is why I use absolute positioning.Stertor
When you scroll down, it'll still be X px from the top, leaving a gap of X px above the bar. That's not how OPs example works. It's X px from the top initially but as you scroll down, it's 0px from the top.Meehan
yeah that would be just be a little javascript to detect the scrolltop position and change the top CSS rule for the main wrapping element.Stertor
Thats how I've always done it, and the js is an if/else with document.getElementById("navbar").style.position = "fixed/relative"; dont even need to change the "top: 0;", you can do the same thing with a footer. I always add "z-index: 1;" though.Alkmaar
This was originally opened about 8 years ago, and things change. Today position fixed should work across all devices and browsers. :)Stertor
A
-1

In your css file:

body {
    padding-top: 0px;
}
Audi answered 25/4, 2019 at 19:33 Comment(1)
But bro this has nothing to do with fixing the nav on the top.Eluviation

© 2022 - 2024 — McMap. All rights reserved.