Minimum / Maximum absolute position in CSS

position: sticky

There have been discussions in the W3C about this in recent years. One proposal is the addition of a sticky value for the position property.

.content {
    position: -webkit-sticky;
    position:    -moz-sticky;
    position:     -ms-sticky;
    position:      -o-sticky;
    position:         sticky;
    top: 10px;
}

This is currently supported in Chrome 23.0.1247.0 and later as an experimental feature. To enable it, enter about:flags for the URL address and press enter. Then search for "experimental WebKit features" and toggle it between enabled and disabled.

On the html5rocks website, there's a working demo.

Strictly speaking, this is an implementation of sticky content, and not a general-purpose way to limit the minimum or maximum position of an element relative to another element. However, sticky content might be the only practical application for the type of the behavior you're describing.


As there is no way to build this for all major browsers without the use of JavasScript I made my own solution with jQuery:

Assign position:relative to your sticky-top-menu. When it reaches the top of the browser window through scrolling the position is changed to positon:fixed.

Also give your sticky-top-menu top:0 to make sure that it sticks to the top of your browser window.

Here you find a working JSFiddle Example.


HTML

<header>I'm the Header</header>
<div class="sticky-top-menu">
  <nav>
    <a href="#">Page 1</a>
    <a href="#">Page 2</a>
  </nav>
</div>
<div class="content">
  <p>Some content...</p>
</div>

jQuery

$(window).scroll(function () {
    var headerTop = $("header").offset().top + $("header").outerHeight();

    if ($(window).scrollTop() > headerTop) {
        //when the header reaches the top of the window change position to fixed
        $(".sticky-top-menu").css("position", "fixed");
    } else {
        //put position back to relative
        $(".sticky-top-menu").css("position", "relative");
    }
});

CSS

.sticky-top-menu {
    position:relative;
    top: 0px;
    width: 100%;
}