I am creating a header that once scrolled to a certain amount of pixels it fixes and stays in place.
Can I do this using just css and html or do i need jquery too?
I have 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; }
The best way to do this is to set a new CSS class for the fixed position that will get assigned to the relevant div when scrolling goes past a certain point. If the trigger point is unknown but should be whenever the sticky element reaches the top of the screen, offset(). top can be used.
above css code, is the class which makes navigation sticky using " position :fixed " property, using this property we make sure, the content will remain positioned as fixed during scroll in HTML page. " top:0; left:0 " gives the position from top of browser, where content should be placed.
To freeze the row/column we can use a simple HTML table and CSS. HTML: In HTML we can define the header row by <th> tag or we can use <td> tag also. Below example is using the <th> tag. We also put the table in DIV element to see the horizontal and vertical scrollbar by setting the overflow property of the DIV element.
You need some JS to do scroll events. The best way to do this is to set a new CSS class for the fixed position that will get assigned to the relevant div when scrolling goes 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'); });
Example fiddle: http://jsfiddle.net/gxRC9/501/
EDIT: Extended example
If the trigger point is unknown but should be whenever the sticky element reaches the top of the screen, offset().top
can be used.
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/
I have modified the Coop's answer. Please check the example FIDDLE Here's my edits:
$(window).scroll(function(){ if ($(window).scrollTop() >= 330) { $('.sticky-header').addClass('fixed'); } else { $('.sticky-header').removeClass('fixed'); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With