search
HomeWeb Front-endCSS TutorialDetailed explanation of usage of position: sticky

Position: sticky in CSS allows us to build some very concise interactions in very few lines of code. It's useful anytime the user wants a UI element to stay in view while scrolling, but not become sticky until the element reaches a specific distance from the top/bottom/left/right side of the scroll viewport.

How can we set a position: sticky?

position: sticky is perfect for iOS style list headers. Scroll the content and watch the title after it hits 0px from the top edge.

.heading{
  background: #ccc;
  height: 50px;
  line-height: 50px;
  margin-top: 10px;
  font-size: 30px;
  padding-left: 10px;
  position: -webkit-sticky;
  position: sticky;
  top: 0px;
}

You want the list title to remain visible if the user scrolls down. If you scroll up, you also want the "Add Item" footer to be visible. Try it! Scroll up and down and watch how the elements stick after reaching the edge of the viewport:

header{
  background: #ccc;
  font-size: 20px;
  color: #282a37;
  padding: 10px;
  position: -webkit-sticky;
  position: sticky;
  top: 0;
}
footer{
  background: #ccc;
  padding: 10px;
  color: #ae81fe;
  position: relative;
  position: -webkit-sticky;
  position: sticky;
}
footer{
  bottom: 0;
}
list{
  border: 1px solid #ccc;
  border-radius: 5px;
  width: 200px;
  margin-left: 20px;
  background: #282a37;
}
item{
  padding: 10px;
  color: #fff;
  display: block;
}
body{
  padding-top: 20px;
  display: flex;
  align-items: flex-start;
}
.abs{
  position: absolute;
  right: 0;
  top: 10px;
}

You can also stick items to the left or right edge. This is a side image viewer with a rotated text description of the image. Scroll it sideways and watch as the description is docked to the left, in view, until a new description pushes it out of the way.

div[description]{
  max-width: 40px;
  height: 300px;
  position: -webkit-sticky;
  position: sticky;
  left: 0; /* become sticky once touching left edge */
}
sidescroller{
  display: flex;
  align-items: center;
  overflow-x: auto;
  overflow-y: hidden;
  background: #000;
}
div[wrapper]{
  flex: 0 0 40px;
  max-width: 40px;
  height: 300px;
  position: -webkit-sticky;
  position: sticky;
  left: 0;
  white-space: nowrap;
  color: #fff;
}
div[item]{
  display: flex;
}
div[description] span{
  display: inline-block;
  background: rgba(0,0,0,.5);
  width: 300px;
  height: 40px;
  transform: rotate(-90deg) translateX(-300px);
  transform-origin: left top 0;
  padding-top: 11px;
  text-align: center;
  text-transform: uppercase;
  color: #fff;
  font-size: 14px;
}
img{
  max-height: 300px;
}

You can even specify a negative number when an element becomes sticky when some or all of it scrolls out of view! This might be useful, for example, if the sidebar menu becomes sticky when scrolled out of view, leaving a small button that when clicked can jump back to the sidebar:

.sidebar{
  background: purple;
  width: 200px;
  height: 300px;
  padding: 20px;
  flex-shrink: 0;
  overflow: visible;
  position: -webkit-sticky;
  position: sticky;
  left: -200px;
}
.sidebar .handle{
  height: 30px;
  width: 30px;
  position: absolute;
  right: -30px;
  top: 0;
  background: purple;
  color: #fff;
  font-weight: bold;
  font-size: 20px;
  padding-left: 8px;
  cursor: pointer;
}
p{
  padding: 20px;
}
.site{
  display: flex;
}

Use position: sticky is very simple.

1. Declare the element as sticky position:sticky (plus any required browser prefix position: -webkit-sticky)

2. Specify the edge of the item to be "sticked" (Top|Right|Bottom|Left).

3. Enter the distance from the edge, and the stickiness will be activated when it is reached.

For example, say you want the title to become sticky when it is 20px from the top of the scroll area:

.header{
  position: -webkit-sticky;
  position: sticky;
  top: 20px;
}

Or scroll to the left edge of the menu out of view like the example above:

.menu{
  width: 200px;
  position: -webkit-sticky;
  position: sticky;
  left: -200px;
}

Notes on position: sticky

Sibling elements

If sibling (adjacent) elements are set to position: sticky, they behaves slightly differently than elements in nested items. Sticky sibling elements are not moved for new elements. Instead, they overlap in place:

Detailed explanation of usage of position: sticky

Sometimes you may want this behavior, but if you do set a background color, otherwise the user will see all Projects are packed into the same small space all at once and it looks like a mess.

On the other hand, if you nest a sticky element into a parent element, like we did in the SsiDelLoad example, then the sticky element will start to move as soon as another sticky element starts touching it , which is a good practice and works a bit like IMO:

Detailed explanation of usage of position: sticky

Overflow (overflow)

Don’t use overflow: auto |scroll|hidden on the parent element of a position:sticky element, which completely breaks stickiness, but overflow: visible does.

Absolute positioning (position:absolute)

If you want to use position:absolute elements inside a sticky element, you must be careful. If your application is running in an older browser that does not support position:sticky, the sticky element will not behave like a relatively positioned element. So an absolutely positioned element will skip it and look up the DOM tree until it finds the next non-static element (absolute|relative fixed position), html will default to the element if not found. In other words, your absolutely positioned element will look different on screen than you expect. If you are building on some older browsers, one might think that the solution to this situation is to set both relative and sticky positioning:

.footerwithAbsolutePositionedeChildren{
position: relative;/*don't forgot this*/
}
/*NOTE: @supports has to be at the root,not nested*/
@supports(position:sticky){
.footerwithAbsolutePositionedeChildren{
position: sticky;
bottom: 20px;/now this won't mess with position in non-sticky browsers*/
}
}

Why not use JavaScript?

You can definitely achieve this using JS. But this will involve a scroll event listener, which is still a very expensive thing to add to your application. Scrolling is one of the most common actions performed by users, and executing JavaScript during these events makes it difficult to maintain stable 60 FPS (frames per second) scrolling. The UI is out of sync with the user's mouse/finger/stylus. This is called rolling jank. There is a special kind of event listener called a passive event listener, which lets the browser know that your events will not stop scrolling, so the browser can better optimize these events. But they're not supported yet in IE or Edge, you'll need the JS fallback anyway.

Additionally, since position:sticky you are not writing to the DOM during scrolling, you are not causing any forced layout and layout recalculation. So the browser is able to move this operation to the GPU and you can scroll very smoothly even when the sticky element is playing. It's especially smooth in mobile Sarari.

Also, writing two lines of declarative CSS is easier than using the JS alternative.

Can I use it now?

position:sticky is supported by many browsers, but not yet in Edge. IE doesn't matter here unless you have contractual obligations in Enterprise Town. If you must have this behavior, there are a lot of polyfills out there, but they all use JavaScript, so you'll get the performance mentioned above. A better option is to design your app so that sticky locations are a slick addition, but the app still doesn't have its functionality.

The above is the detailed content of Detailed explanation of usage of position: sticky. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
CSS Inclusion: Choosing the Right Method for Your ProjectCSS Inclusion: Choosing the Right Method for Your ProjectMay 16, 2025 am 12:02 AM

ThebestmethodforincludingCSSdependsonprojectsizeandcomplexity:1)Forlargerprojects,useexternalCSSforbettermaintainabilityandperformance.2)Forsmallerprojects,internalCSSissuitabletoavoidextraHTTPrequests.Alwaysconsidermaintainabilityandperformancewhenc

This Isn't Supposed to Happen: Troubleshooting the ImpossibleThis Isn't Supposed to Happen: Troubleshooting the ImpossibleMay 15, 2025 am 10:32 AM

What it looks like to troubleshoot one of those impossible issues that turns out to be something totally else you never thought of.

@keyframes vs CSS Transitions: What is the difference?@keyframes vs CSS Transitions: What is the difference?May 14, 2025 am 12:01 AM

@keyframesandCSSTransitionsdifferincomplexity:@keyframesallowsfordetailedanimationsequences,whileCSSTransitionshandlesimplestatechanges.UseCSSTransitionsforhovereffectslikebuttoncolorchanges,and@keyframesforintricateanimationslikerotatingspinners.

Using Pages CMS for Static Site Content ManagementUsing Pages CMS for Static Site Content ManagementMay 13, 2025 am 09:24 AM

I know, I know: there are a ton of content management system options available, and while I've tested several, none have really been the one, y'know? Weird pricing models, difficult customization, some even end up becoming a whole &

The Ultimate Guide to Linking CSS Files in HTMLThe Ultimate Guide to Linking CSS Files in HTMLMay 13, 2025 am 12:02 AM

Linking CSS files to HTML can be achieved by using elements in part of HTML. 1) Use tags to link local CSS files. 2) Multiple CSS files can be implemented by adding multiple tags. 3) External CSS files use absolute URL links, such as. 4) Ensure the correct use of file paths and CSS file loading order, and optimize performance can use CSS preprocessor to merge files.

CSS Flexbox vs Grid: a comprehensive reviewCSS Flexbox vs Grid: a comprehensive reviewMay 12, 2025 am 12:01 AM

Choosing Flexbox or Grid depends on the layout requirements: 1) Flexbox is suitable for one-dimensional layouts, such as navigation bar; 2) Grid is suitable for two-dimensional layouts, such as magazine layouts. The two can be used in the project to improve the layout effect.

How to Include CSS Files: Methods and Best PracticesHow to Include CSS Files: Methods and Best PracticesMay 11, 2025 am 12:02 AM

The best way to include CSS files is to use tags to introduce external CSS files in the HTML part. 1. Use tags to introduce external CSS files, such as. 2. For small adjustments, inline CSS can be used, but should be used with caution. 3. Large projects can use CSS preprocessors such as Sass or Less to import other CSS files through @import. 4. For performance, CSS files should be merged and CDN should be used, and compressed using tools such as CSSNano.

Flexbox vs Grid: should I learn them both?Flexbox vs Grid: should I learn them both?May 10, 2025 am 12:01 AM

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!