Search code examples
htmlcssheaderoverflowfixed

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 of a scrollbar.

I'm worried that this is one of those CSS use cases which should be trivial, but might, in fact, be impossible. Anyone willing to prove me wrong?


Solution

  • 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