What is the best approach to restricting an absolutely positioned element's position, ideally in pure CSS?
I know that the following isn't possible but I guess what I'm looking for would look something like:
.stickyElement{
bottom-max:auto;
bottom-min:0px;
top-max: auto;
top-min: 100px;
}
That would allow an element to move to a position no less than 100px from the top of it's containing, positioned element.
An example (and my initial) use case for this is a menu that scrolls as part of a page but stops scrolling when it hits the top of a viewport. (Sticky menus?) an example of which can be seen on this page: http://spektrummedia.com/startups
I fully expect that this is not possible without using some Javascript but I thought I'd put it out there.
position: relative places an element relative to its current position without changing the layout around it, whereas position: absolute places an element relative to its parent's position and changing the layout around it.
The position CSS property sets how an element is positioned in a document. The top , right , bottom , and left properties determine the final location of positioned elements.
As long as you structure your HTML so that the elements follow a logical order that makes sense when rendered without CSS, there is no reason why using absolute positioning should be considered bad practice.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With