Look at the renderings first

This navigation bar will now automatically change to a fixed top if it reaches the top.

The implementation code is as follows

position:sticky;
top: 44px;
Copy the code

The principle of

  1. Position :sticky is a new attribute for CSS positioning.
  2. It can be said that the combination of relative positioning and fixed positioning;
  3. It is mainly used to monitor scroll events;
  4. In simple terms, in the sliding process, when the distance between an element and its parent reaches the sticky sticky positioning requirement (for example, top: 100px); Position :sticky

Matters needing attention

  1. The parent element cannot have overflow:hidden or overflow: Auto attributes.
  2. You must specify one of the four values top, bottom, left, or right. otherwise, you are in a relative position
  3. The height of the parent element cannot be lower than that of the sticky element
  4. The sticky element is valid only within its parent element