I try to put a sticky div inside of a wrapper. It's not working. The sticky div seems to attach to the window. How do I solve this. HTML: <div class="wrapper"> <div class="sticky-div"> <nav> <ul> <li><a href="#portfolio">Portfolio</a></li> <li><a href="#about">About</a></li> <li><a href="#contact">Contact</a></li> </ul> </nav> </div> </div> Code (markup): CSS: .wrapper { margin: 0 auto; width: 960px; border: 1px solid #000; } .sticky-div { padding: 0; position: fixed; z-index: 100; background: #e8e8ea; display: block; height: 50px; top: 0; right: 0; } Code (markup): Thank you,
You scroll down this page and you'll see part of the header of the page stick to the top of the window. Some div sticks to the left, right, bottom, any where on the page you wanted it to.
This may help you for this ! <style type="text/css"> .wrapper { margin: 0 auto; width: 960px; border: 1px solid #000; position: relative; } .sticky-div { padding: 0; position: absolute; z-index: 100; background: #e8e8ea; display: block; height: 50px; top: 0; right: 0; } .sticky-div.fixed{ position:fixed; right: auto } </style> <header style="height:1500px"> <div class="wrapper"> <div class="sticky-div"> <nav> <ul> <li><a href="#portfolio">Portfolio</a></li> <li><a href="#about">About</a></li> <li><a href="#contact">Contact</a></li> </ul> </nav> </div> </div> </header> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript"> var el = $('.sticky-div'), el_top = el.offset().top, el_pos = el.offset().left; $(window).scroll(function() { if (!el.hasClass('fixed') && $(this).scrollTop() > el_top + el.height()) { el.addClass('fixed'); el.css({ "left": el_pos }) } else if (el.hasClass('fixed') && $(this).scrollTop() <= el_top) { el.removeClass('fixed'); el.css({ "left": "auto" }) } }); </script> HTML:
Fixed position is relative to the window. If you want it relative to its parent element then the parent element need to have position:relative, and the "sticky" div needs position absolute. I have a piece on it in this snippet about positioning