Is it possible to create a sticky sidebar that follows you down the
page but which stays inside of its container element [using HTML/CSS only]?
Like this:
http://codepen.io/jamesdarren/full/ivmcH
... but without the JavaScript.
The answer is: At the present time, it depends on your browser.
CSS has an experimental positioning value named sticky
.
By setting your sidebar to position: sticky
it can remain fixed inside its parent container and the viewport, as opposed to just the viewport.
Here's how Google Developers describes it:
position: sticky
is a new way to position elements and is
conceptually similar to position: fixed
. The difference is that an
element with position: sticky
behaves like position: relative
within its parent, until a given offset threshold is met in the
viewport.
Here's MDN's take:
Sticky positioning is a hybrid of relative and fixed positioning. The
element is treated as relative positioned until it crosses a specified
threshold, at which point it is treated as fixed positioned.
Currently, however, only Firefox and Safari support sticky positioning.
Here are two demos of position: sticky
(FF & Safari only):
http://html5-demos.appspot.com/static/css/sticky.html
http://jsfiddle.net/daker/ecpTw/light/
Here's a position: sticky
polyfill:
https://github.com/filamentgroup/fixed-sticky
from the polyfill readme:
The most overlooked thing about position: sticky
is that sticky
elements are constrained to the dimensions of their parent elements.
Lastly, should you decide to loosen your language constraints to allow scripting, here's a simple, effective and reliable solution for a sticky sidebar:
Tether
Tether is a JavaScript library for efficiently making an absolutely
positioned element stay next to another element on the page.
Tether includes the ability to constrain the element within the
viewport, its scroll parent, any other element on the page, or a fixed
bounding box.
http://github.hubspot.com/tether/