Position :sticky

In the development of mobile app, often encounter the need for such a situation — the site scrolling to a certain height, let a part of the content as a Navbar, that is, the top display, we will generally use JS monitor scroll event to achieve, but the new CSS attribute position:sticky can be simple implementation

I’m not the last to know

Position specifies the bit type. The value types can be static, relative, Absolute, fixed, inherit, and sticky. Sticky is a new property released by CSS3. The sticky attribute is what I want to talk about today

Position: sticky usage

  • Stickily positioned element is a calculated element with sticky positioning properties.
  • The simple way to think about it is: within the target area, it behaves like position:relative; During the sliding process, when the distance between an element and its parent reaches the sticky position requirement (e.g., top: 100px); Position: Sticky When the effect is equivalent to fixed positioning, fixed to the appropriate position.
  • A. relative B. fixed C. relative D. fixed
  • The element’s fixed relative offset is relative to its nearest ancestor element that has a scroll box. If none of the ancestor elements can be scrolled, then the element’s offset is calculated relative to the viewport.

Position :sticky conditions of use

1. The parent element cannot have overflow:hidden or overflow:auto properties.

2. You must specify one of the four values: top, bottom, left, and right. otherwise, the position will only be relative

3. The height of the parent element cannot be lower than the height of the sticky element

4. Sticky elements are valid only in their parent elements

example

  • When the mouse slides to a certain height, trigger position:sticky positioning requirements, let “popular, new, selected” fixed 44px from the top place.

  • CSS code

.tab-control{
  position: sticky;
  top: 44px;
}
Copy the code
  • HTML area
<tab-control class="tab-control" :titles="[' popular ',' new ',' Selection ']"></tab-control>
Copy the code

Note compatibility in Web development:

Sticky is still an experimental attribute and is not a W3C recommendation. It also happens because listening for Scroll events to implement a sticky layout that puts the browser into slow scrolling mode, which is contrary to the browser’s desire to improve the scrolling experience with hardware acceleration. The only browsers used for this property are FireFox and Safari for iOS

Use sticky “pits”

  • 1. Sticky does not trigger BFC.

  • 2. Z – the index is invalid,

  • 3. When the height of the parent element: 100%, the sticky attribute will be invalid after the page slide to a certain height.

  • 4.IE low version does not support the use of sticky

Small program custom navigation bar using sticky:

Sticky can be effective again small program end! This property is especially useful for custom navigation