Css issues with fixed positioning

92 2
<html>
<head>
 <style>
 #blog_header{
 width: 100%;
 height: 130px;
 background: #993399;
 position: fixed;
 }
 #nav_ul,#nav_ul li{
 height: 30px;
 display: inline;
 line-height: 30px;
 }
 </style>
</head>
<body>
 <div id="blog_header">
 <ul id="nav_ul">
 <li>news</li>
 <li>technology</li>
 <li>forum</li>
 <li>about me</li>
 </ul>
 </div>
 <div id="main_wrapper">
 content
 </div>

For a piece of code, the navigation bar will stay at the top end of the page, but the current problem is fixed after positioning out of the document, and the navigation bar is no longer placeholder, resulting in the following # main wrapper 's starting position and the # blog header?

There are some information on the internet. It's an empty div, but it isn't the right one.

5 Answers

128 5
#nav {
 position: sticky;
 top: 0;
}

Perfect solution.
Unfortunately, supports.

So attach a polyfill:

var Sticky = function() {
 var s = [], 
 support = (function testSupport() {
 var div = document.createElement("div");
 var st = ["sticky","-webkit-sticky"];
 return st.some(function(x) {
 div.style.position = x;
 return div.style.position === x;
 });
 }());
 function Sticky(o) {
 var self = this;
 s.push(self);
 self[0] = o;
 var placeholder = document.createElement("div");
 self.placeholder = placeholder;
 placeholder.classList.add("placeholder");
 self.fixed = false;
 self.posit = posit;
 function posit() {
 var rect;
 if (self.fixed) {
 rect = placeholder.getBoundingClientRect();
 self.staticTop = rect.top + window.pageYOffset;
 } else {
 rect = o.getBoundingClientRect();
 self.staticTop = rect.top + window.pageYOffset;
 }
 }
 posit();
 }
 Sticky.prototype.stick = function() {
 if (support)
 return;
 var o = this[0], 
 top = this.staticTop;
 var placeholder = this.placeholder, fixed = this.fixed;
 console.log(top);
 if (top> window.pageYOffset && fixed) {
 placeholder.parentNode.removeChild(placeholder);
 o.classList.remove("sticky");
 fixed = false;
 } else if (top <= window.pageYOffset &&!fixed) {
 o.parentNode.insertBefore(placeholder, o);
 o.classList.add("sticky");
 fixed = true;
 }
 this.fixed = fixed;
 };
 if (!support) {
 window.addEventListener("scroll", function() {
 s.forEach(function(x) { x.stick(); });
 });
 window.addEventListener("resize", function() {
 s.forEach(function(x) { x.posit(); });
 s.forEach(function(x) { x.stick(); });
 });
 } else {
 console.log("support");
 }
 return Sticky;
}();

Use methods: new Sticky(document.querySelector("#nav"));

...