Skip to content Skip to sidebar Skip to footer

Fixed Header Inside Scrolling Block

I'm trying to create a block which may or may not have a scrollbar, with a header that does not scroll. The trick is that the width of the header should be affected by the presence

Solution 1:

Solution 2:

You cannot do this with CSS alone. We must use javaScript. With jQuery you can do the following

var cw = $('#container').innerWidth(),
    cs = $('#container').scrollTop();

    $('#header').css({
        'width': cw + "px"
    });

    $('#container').scroll(function() {
        $('#header').css({
            'top': $('#container').scrollTop(),
        })
    })

Check working example at http://jsfiddle.net/VswxL/2/

Solution 3:

I haven't figured out how to do this with CSS alone. So, here's a solution which uses JavaScript (here, jQuery), but only runs when he content changes. If the size of your wrapper depends on the size of the window, you may also need to run it on resize. Here's the heart of it:

$.fn.fitTo = function(target){
    var $el = $(this);
    $(target).bind('refit', function(){
        $el.width(this.clientWidth);
    });
}

Call $header.fitTo($content) to bind the header to a custom refit event on the element with the content. Now, whenever the content changes such that a scroll bar may have appeared or disappeared, do…

$content.trigger('refit');

…and the width of the header is reset to the clientWidth of the element containing content. The header must be outside the scrolling element.

Working example

Post a Comment for "Fixed Header Inside Scrolling Block"