I'm creating a header that will fix and stay in place once scrolled to a certain number of pixels.
Can I do this using just css and html or do I need jquery too?
I created a demo so you can understand. Any help would be great!
http://jsfiddle.net/gxRC9/4/
body{ margin:0px; padding:0px; } .clear{ clear:both; } .container{ height:2000px; } .cover-photo-container{ width:700px; height: 348px; margin-bottom: 20px; background-color:red; } .small-box{ width:163px; height:100px; border:1px solid blue; float:left; } .sticky-header{ width:700px; height:50px; background:orange; postion:fixed; }
P粉5170907482023-10-13 20:34:56
I modified Coop's answer. Please check the example FIDDLE Here are my modifications:
$(window).scroll(function(){ if ($(window).scrollTop() >= 330) { $('.sticky-header').addClass('fixed'); } else { $('.sticky-header').removeClass('fixed'); } });
P粉2441552772023-10-13 11:27:00
You need some JS to handle scroll events. The best way would be to set a new CSS class for a fixed position that will be assigned to the relevant div when scrolling past a certain point.
HTML
<div class="sticky"></div>
CSS
.fixed { position: fixed; top:0; left:0; width: 100%; }
jQuery
$(window).scroll(function(){ var sticky = $('.sticky'), scroll = $(window).scrollTop(); if (scroll >= 100) sticky.addClass('fixed'); else sticky.removeClass('fixed'); });
Fiddle example: http://jsfiddle.net/gxRC9/501/
Edit: Extended example
If the trigger point is unknown, but should trigger when the sticky element reaches the top of the screen, you can use offset().top
.
var stickyOffset = $('.sticky').offset().top; $(window).scroll(function(){ var sticky = $('.sticky'), scroll = $(window).scrollTop(); if (scroll >= stickyOffset) sticky.addClass('fixed'); else sticky.removeClass('fixed'); });
Extended example fiddle: http://jsfiddle.net/gxRC9/502/