pandarouge
pandarouge

Reputation: 97

Absolute element becomes fixed when vertical scrolling past it

I am currently making a website of my own based on HTML, CSS and a tiny bit of Javascript/jQuery. (I'm bad with JavaScript. Never really tried to learn it, just copied codes off.)

I'm trying to have my navigation bar or "table des matières" (site is in french), which is a position: absolute; element, become a position: fixed; element once you scroll past it, something like plus.google.com (Google+'s sub-header).

Here is my code so far: http://codepen.io/anon/pen/FnCch

I just don't see how to make it happen.

Also, I would like some insight on how I can make my page look better. I'm trying a full-page design, something like Apple's, instead of the usual margin and table-like site. My brother said the effects and the coding was amazing but that it looked disgusting (badly aligned, I'm having trouble with that, fonts don't go well with each other, he says everything is way too big... etc)

http://remyses.neocities.org/tpe2014.html

Upvotes: 0

Views: 356

Answers (3)

jamie
jamie

Reputation: 152

I agree, bootstrap is an awesome framework to get things going with the proper JS to make anything you want adaptive for different devices. From the design aspect you might also want to use EMs for fonts instead of px so they will be easier to read on all devices as well.

Also within bootstrap there is a plugin called affix for exactly what you are trying to do: Link to Affix

Upvotes: 1

Shannon
Shannon

Reputation: 837

Use the following javascript to change the styling of the nav bar when you scroll the window down.

// trigger on scroll event    
window.onscroll = function () {
  // get scrollbar position
  var doc = document.documentElement, body = document.body;
  var top = (doc && doc.scrollTop  || body && body.scrollTop  || 0);

  // get menu 
  var menu = document.getElementById("cssmenu");

  // if scrollbar past menu height: set position to fixed, 
  if (top > (menu.offsetHeight + menu.offsetTop)) {
     menu.style.position = "fixed";
  } 
  // set position to absolute
  else {
     menu.style.position = "absolute"; 
  }
};

See here: http://codepen.io/anon/pen/xnsBC

Upvotes: 1

Haiz
Haiz

Reputation: 171

For styling, without tables you can use div tags. CSS frameworks like bootstraps are also very helpful. For the navigation bar to stay, you will have to make it position:fixed instead of position:absolute. If you want the use to scroll the page, then the nav bar stay at the top of the screen, you would need some javascript.

Upvotes: 0

Related Questions