Despite the convenience of position: sticky, I hardly see this property on sites. Currently the property is supported by 94% of browsers.
Data from the site Can I Use
I first encountered sticky positioning in an article in which the author fixed the menu with two lines, and later the interactive elements on the page. And I thought, "Without the help of Java Script, wow!" I was really glad that this opportunity appeared.
Four years ago, everyone was familiar with four types of positioning:
static, relative, absolute, fixed.
Items with position
static
and
relative
keep their position in the document flow, while
absolute
and
fixed
drop out of the stream.
"Sticky" positioning is well described by this quote from the site MDN .
Sticky positioning can be thought of as a hybrid of relative and fixed positioning. An attached element is considered relatively positioned until it crosses a given threshold, after which it is considered fixed until it reaches its parent's boundary.
How position: sticky works
Element with
position: sticky
moves within the nearest parent. The place where the element “sticks” is influenced by property values:
top, right, bottom, left, padding, margin and transform.
After the position property is set to
sticky
the size of the parent container will not change, adjacent elements will not move to the freed space.
We can say that
position: sticky
a hybrid of not only relative and fixed positioning, but also absolute (
position: absolute
).
The item remains in the stream and retains its position. When rewinding starts, the element behaves as if the property had become fixed. Finally stops in a container on top of another item.
Examples.
The element will “stick” to the top edge of the browser window.
. sticky-element {
position : sticky;
top : 0 ;
}
When adding styles to an element
top: 3rem
The element will "stick" to the top edge of the browser window, indented by 3rem.
. sticky-element {
position : sticky;
top : 3 rem ;
}
If we add to the element
margin: 2rem
, then the element will “unstick” 2rem from the bottom edge of the container.
. sticky-element {
position : sticky;
top : 0 ;
margin : 2 rem ;
}
The element will “stick” to the bottom edge of the browser.
The element "sticks" to the bottom edge, then to the top.
. sticky-element {
position : sticky;
top : 0 ;
bottom : 0 ;
}
The element will “stick” inside the scrolling block, not to the edge of the browser.
. container {
overflow : auto ;
height : 15 rem ;
}
. sticky-element {
position : sticky;
top : 0 ;
}
Application
With position: sticky, you can pin the menu or footer on the site, as well as the sidebar. Make a slider or gallery.