introduce

Position :sticky is a new attribute for CSS positioning. It can be said that the combination of relative positioning and fixed positioning; It is mainly used to monitor scroll events; 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

Conditions of use

  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
  nav{
    position: sticky;
    top: 0;
  }
Copy the code

All the code

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/index1.js"></script> < meta name = "viewport" content = "width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user-scalable=no"/> <style> body{ overflow: scroll; } nav{ position: sticky; top: 0; display: flex; justify-content: space-between; background: green; } h3{ font-size: 20px; color: white; } ul li{ line-height: 150px; height: 150px; font-size: 20px; border-bottom: 1px solid orange; list-style: none; } </style> </head> <body> The first demo of sticky < / h1 > < nav > < h3 > navigation A < / h3 > < h3 > navigation B < / h3 > < h3 > navigation C < / h3 > < nav > < ul > < li > 1 < / li > < li > 2 < / li > < li > 3 < / li > < li > 4 < / li >  <li>5</li> <li>6</li> <li>7</li> <li>8</li> <li>9</li> <li>10</li> </ul> </body> </html>Copy the code