Search code examples
htmlcsspositioning

alignment of a element while y scroll


What i want to is when somebody use y scroll even in that case the header (which contains days and dates should be visible.) Please check the screen shot

Something using position:fixed and z-index etc.

(example i have seen :-- when u open stack-overflow and ur JavaScript is disabled, then in that case a red colored message will appear and keep appearing even if u scroll down the page.)

So What i want to do is:--

Initially at page load this row will the be in between the page (as there are lot of other things above and once user scroll down it should be visible to user ie this sticks with the top of the page)


Solution

  • If I understand you correctly, you are looking for an element that is not located at the top of the page, but sticks to the top when you scroll down past it? This can be done with css and a little JavaScript magic (jQuery used for brevity):

    /* CSS - you should add width, height, padding as needed */
    #your_element { position:relative;}
    

    Your element will behave normally if JS is disabled. Otherwise, the following snippet makes it dynamic:

    win = $(window);
    element = $('#your_element');
    
    if (element.length) {                // <-- Make sure element exists
        win.scroll(function () {         // <-- When scrolling do the following
            if (win.scrollTop() > 100) { // <-- Adjust number.  Explanation to follow
                element.css({'position':'fixed', 'top':'0px'});
            } else {
                element.css({'position':'relative', 'top':'auto'});
            }
        });
    }
    

    Now you just have to adjust the value 100 to equal the distance between the top of the page and the top of your element. So, if your element is 250px from the top, you would use 250. If you are not sure you can play around with it until you get something that looks smooth.