Can I keep a DIV always on the screen, but not always in a fixed position?

Rachel picture Rachel · Dec 7, 2011 · Viewed 39k times · Source

I have a master form for my website, and I want to dock a div to the top of the content area inside the master form. This div should always be visible despite scroll position. Is this possible?

A picture would explain it better.

enter image description here

Answer

zzzzBov picture zzzzBov · Dec 8, 2011

I posted a sample as a comment, so I suppose I'll write out a full answer to this.

The markup is pretty straight-forward, but there are some important notes for each section.

HTML

<div id="page">
    <div id="header">
        <div id="header-inner"> <!-- Note #1 -->
            <img src="http://placehold.it/300x100" />
        </div>
    </div>
    <div id="content">
        <!-- Some Content Here -->
    </div>
</div>

CSS

#page {
    padding: 100px;
    width: 300px;
}

#header,
#header-inner { /* Note #1 */
    height: 100px;
    width: 300px;
}

.scrolling { /* Note #2 */
    position: fixed;
    top: 0;
}

JavaScript

//jQuery used for simplicity
$(window).scroll(function(){
  $('#header-inner').toggleClass('scrolling', $(window).scrollTop() > $('#header').offset().top);

  //can be rewritten long form as:
  var scrollPosition, headerOffset, isScrolling;
  scrollPosition = $(window).scrollTop();
  headerOffset = $('#header').offset().top;
  isScrolling = scrollPosition > headerOffset;
  $('#header-inner').toggleClass('scrolling', isScrolling);
});

Note #1

The scrolling header will be attached to the top of the page using position: fixed, but this style will remove the content from content flow, which will cause the content to jump unless its container maintains the original height.

Note #2

Styles belong in CSS, however it may be difficult to properly align some elements with their original position. You may need to dynamically set the left or right css property via JavaScript.