CSS basics-use position: sticky to implement sticky Layout
Introduction
I have previously written an article to explain several common attributes of position: Explanation of position of CSS attributes
We generally know the following common examples:
{position: static;position: relative;position: absolute;position: fixed;}
The following three values are available at https://developer.mozilla.org/zh-cn/docs/web/css/position:
/* Global Value */position: inherit; position: initial; position: unset;
Most of them are not used.Position: stickyRight. This attribute value is still in the test phase. How to describe it?
Sticky: the object follows the regular flow in normal conditions. It is likerelative
Andfixed
When the screen is in the regular flow layout, when the scroll to the outside of the screen, the performance is as follows:fixed
. This property shows the actual adsorption effect you see.
Common scenarios: when the distance between an element and the top of the page is greater than 0 PX (Viewport, that is, the reference for fixed positioning), the element is positioned as relative. When the distance between an element and the page view is less than 0 PX, the element is positioned as fixed, which is fixed on the top.
Code:
{ position: -webkit-sticky; position: sticky; top: 0;}
For example:
It is larger than 20px from the top of the page, as shown in
position:relative
;
Less than 20 px from the top of the page, as shown in
position:fixed
;
Application
position:sticky
Fixed the header navigation bar
Html code:
<Div class = "con"> <div class = "samecon">
CSS code:
.samecon h2{ position: -webkit-sticky; position: sticky; top: 0; background:#ccc; padding:10px 0;}
Similarly, the side navigation bar can also be exceeded and fixed.
Effective rules
Top, right, bottom, or left must be specified to take effect for the viscous positioning. Otherwise, the behavior is the same as the relative positioning.
- And
top
Andbottom
At the same time,top
High priority,left
Andright
At the same time,left
High priority.
Setposition:sticky
The overflow attribute of any parent node of the element must be visible. Otherwiseposition:sticky
Does not take effect. Here we need to explain:
- If
position:sticky
Any parent node of the element is positionedoverflow:hidden
, The parent container cannot be rolled, soposition:sticky
The element does not have to scroll and then be fixed.
- If
position:sticky
Any parent node of the element is positionedposition:relative | absolute | fixed
The element is located relative to the parent element, but not relative to the viewprot.
Reaches the set threshold. This is easy to understand.position:sticky
The element isrelative
Orfixed
It is determined by whether the element has reached the set threshold.
Compatibility
The compatibility of this attribute is not very good. It is still a test property and is not the W3C recommendation standard.