Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minimum / Maximum absolute position in CSS

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.

like image 373
Lewis Avatar asked Apr 23 '13 08:04

Lewis


People also ask

What is absolute and relative position in CSS?

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.

What is CSS position property?

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.

Should you use absolute positioning CSS?

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.


1 Answers

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.

like image 199
Matt Coughlin Avatar answered Sep 18 '22 05:09

Matt Coughlin