Briefly
An element with position
"sticks" to the screen when scrolling, until it meets the edge of its parent block.
Example
Let's make a "sticky" header, as well as a "sticky" block in the lower right corner for each of <section>
:
h1 { position: sticky; top: 15px;}.squares__item:last-of-type { position: sticky; bottom: 15px;}
h1 { position: sticky; top: 15px; } .squares__item:last-of-type { position: sticky; bottom: 15px; }
How to understand
Blocks with "sticky" positioning behave like position
and position
at the same time. While the block has not reached the specified distance from the edge of the browser window, it behaves as if it’s relatively positioned. When the block reaches this point, it will behave as if we specified position
. And when it meets the opposite edge of the parent, it will again behave as position
.
How to write
.block { position: sticky; top: 15px;}
.block { position: sticky; top: 15px; }
For a block that should be positioned "sticky," we specify position
and the position relative to the browser window. In this example, the block will "stick" at a distance of 15 pixels from the top edge of the window.
Tips
💡 If the required element takes up the entire height of the parent block (if it is the only one in the block or simply the tallest among neighboring elements), then position
will not work.
💡 When scrolling vertically, only the top
and bottom
properties work; when scrolling horizontally, left
and right
do. Or their logical equivalents inset
.
💡 position
can be specified within a parent with overflow
or overflow
.
💡 If you specify a greater number of pixels for the element than the parent allows, the element will immediately align with the opposite edge of the parent block, but will not go outside the block.
In practice
Advice 1
🛠 With this positioning, it is convenient to create a sticky header - if it is a direct descendant of body
, then by setting the header position
, we will get a static header when the screen loads, and when scrolling the page - fixed at the top.