search
HomeWeb Front-endJS TutorialCSS 'position: sticky' - Introduction and Polyfills

CSS

Key Points

    The
  • CSS's position: sticky property allows the navigation bar or other elements to remain visible when the user scrolls without being pinned to the page. This property acts like a static position within its parent element until the given offset threshold is reached, at which point it is like the value is set to fixed .
  • The traditional way to achieve this effect involves JavaScript, where scrolling events of a page are listened to and use JavaScript to change the values ​​of the position and top properties based on the current position of the viewport. However, when the element's position changes to fixed , this method can cause problems, causing it to leave the page stream and the element below "jumps up".
  • Currently, the browser support for the "position: sticky" attribute is limited. However, there are some polyfills that can be used to provide this feature, including fixed-sticky for the Filament Group, position–sticky- for Matthew Phillips, and Stickyfill for Oleg Korsunsky.

If you have read Annarita Tranfici's article "Obvious Design always wins", you may agree with her:

People expect to see common patterns: find the main menu at the top of the page, find the search box at the top right corner, find the footer at the bottom, and so on.

I agree that people expect certain components of the website to be placed in a specific location, which, in my opinion, is more important for the main menu.

Sometimes, due to customer requirements or because we have determined that this is the best approach, we may need the main navigation to always be visible on the page without pinning it in place, basically following the page content. In recent years, many JavaScript-based solutions have been released because CSS alone cannot complete this task.

In this article, we will discuss position: sticky, which is the new CSS solution to this problem.

What problems do we solve?

Before discussing the new value of this position property, let us better understand the problem we are trying to solve.

Suppose the main menu of our wonderful website is after the title, but is still at the top of the page (not in the sidebar) and takes up all available widths. This might look like this:

CodePen sample link

What we want to achieve is that when the user scrolls the page, once the menu is united at the top of the viewport, the menu will not scroll outside the view, but will stick to the top position - just like it applies position: fixed same (only when it reaches the top of the viewport).

To achieve this with traditional code, we need to add some JavaScript. We listen for scrolling events on the page and use JavaScript to change the values ​​of the position and top properties based on the current position of the viewport. Specifically, when the menu is at the top of the viewport, we need to add top: 0 and position: fixed to the menu, otherwise the attribute will be restored to its default value.

Another similar approach is to create a class in our CSS that contains these values ​​and then add and remove the class using JavaScript as needed, which might look like this:

var menu = document.querySelector('.menu')
var menuPosition = menu.getBoundingClientRect().top;
window.addEventListener('scroll', function() {
    if (window.pageYOffset >= menuPosition) {
        menu.style.position = 'fixed';
        menu.style.top = '0px';
    } else {
        menu.style.position = 'static';
        menu.style.top = '';
    }
});

Note that this code snippet does not handle older versions of Internet Explorer. If you need to deal with these browsers (poor you!), I will provide some polyfill options that you can consider.

The real-time demonstration of this second step is as follows:

CodePen sample link

But wait! Can you find the problem caused by this code? Many implementations I have seen, including those we have developed so far, have not taken into account an important issue. When we change the position of the element to fixed, it leaves the page's stream, so the element below will "jump up" approximately equal to the number of pixels at the height of the element (the height of this "jump" depends on margins, borders, etc. ).

A possible solution is to inject a placeholder element of the same size as the element we want to "paste" so that when we update the style of the sticky element, there is no jumping. Furthermore, if the correct value has been set, we do not want to reassign the value repeatedly for no reason. Finally, we want to adopt the technique I described using the CSS class.

The final version of JavaScript code is as follows:

var menu = document.querySelector('.menu');
var menuPosition = menu.getBoundingClientRect();
var placeholder = document.createElement('div');
placeholder.style.width = menuPosition.width + 'px';
placeholder.style.height = menuPosition.height + 'px';
var isAdded = false;

window.addEventListener('scroll', function() {
    if (window.pageYOffset >= menuPosition.top && !isAdded) {
        menu.classList.add('sticky');
        menu.parentNode.insertBefore(placeholder, menu);
        isAdded = true;
    } else if (window.pageYOffset < menuPosition.top && isAdded) {
        menu.classList.remove('sticky');
        menu.parentNode.removeChild(placeholder);
        isAdded = false;
    }
});

This is the declaration block of the sticky class:

.sticky {
    top: 0;
    position: fixed;
}

The final result is shown in this next demo:

CodePen sample link

Now that you have a good grasp of what the problem is and what the possible JavaScript-based solution is, it's time to embrace modernization and discuss what this position: sticky is about.

What is position: sticky?

If you bravely read the previous section carefully, you might be wondering "Why can't the browser do this for me?" I'm glad you asked!

sticky is a new value introduced for the CSS position property. This value should behave like position: static within its parent element until the given offset threshold is reached, in which case it is like the value is set to fixed . In other words, by using position: sticky, we can solve the problems discussed in the previous section without JavaScript.

Reviewing our previous example and using this new value, we can write:

.menu {
    margin: 0;
    padding: 0;
    width: 100%;
    background-color: #bffff3;
    position: sticky;
}

The browser will do the rest! It's that simple.

Browser support and Polyfills

The support for this new value is currently very bad. Here is the stack situation for each browser:

  • Firefox 26 – Supported by setting css.sticky.enabled to "true" under about:config.
  • Chrome 23 – Supported by enabling Experimental Web Platform Features in chrome://flags.
  • Chrome 38(?) – The Chrome team recently removed this feature from Blink, so it is currently unavailable in Chrome Canary (version 38.x), even with the flag. You can read the bug report explaining the removal, but we suspect this feature will be reimplemented soon and may not interrupt the support of the stable version.
  • Safari 6.1 – Support this value using the -webkit vendor prefix (i.e. position: -webkit-sticky)
  • Opera 23 – Supported by enabling Experimental Web Platform Features in about:flags.
  • Internet Explorer – Not supported (see status)

See position: sticky on Can I Use… for all details.

Luckily, there are many polyfills to choose from:

  • Filament Group's fixed-sticky (requires jQuery)
  • Matthew Phillips' position–sticky- (detection with Modernizr)
  • position: sticky
  • in Philip Walton's Polyfill.js library
  • Fabrice Weinberg's position: sticky CodePen Demo (JQuery required)
  • Oleg Korsunsky's Stickyfill (IE9)

Demo

The following demonstration shows the actual effect of position: sticky. As mentioned before, to make it work, and depending on the browser you are using, you may need to activate a flag.

CodePen sample link

Conclusion

Although this new feature doesn't have good browser support, you may also rather use polyfill, if you define alternative styles with Modernizr, it will gracefully downgrade to the default position: static or position: fixed.

If you have tried this property or know of any other polyfill, please let us know in the comments.

FAQs about CSS Position Sticky (FAQ)

What is the difference between CSS position sticky and other CSS locations?

CSS position: sticky is a mixture of relative positioning and fixed positioning. It allows an element to behave like a relative position within its parent element until it reaches a given scroll point, at which point it becomes a fixed position. This is different from other CSS locations. For example, the "relative" position allows you to position an element relative to the normal position of the element, while the "fixed" position positions the element relative to the browser window, and it won't move even if the page is scrolled. The "absolute" position locates the element relative to the most recent positioned ancestor, "static" is the default value, and locates the element according to the normal flow of the page.

Why does my CSS position sticky not work?

Your CSS position: sticky doesn't work for several reasons. A common reason is that the parent element's overflow attribute is set to hidden, auto or scroll. Another reason may be that the sticky element has a higher sibling than it, causing it to scroll out of the viewport. Also, make sure the sticky element is not a table element, because in some browsers, CSS position: sticky does not work with table elements.

How to make CSS position sticky work on all my browsers?

While CSS position: sticky is widely supported in modern browsers, it may not work in some older versions. To ensure compatibility across all browsers, you can use polyfill. polyfill is a script that provides the technology you expect to provide natively to the browser. A popular polyfill for CSS position: sticky is Stickyfill.

Can I use CSS position sticky with other CSS properties?

Yes, you can use CSS position: sticky with other CSS properties. For example, you can use it with z-index to control the stacking order, or with box-shadow to create a shadow effect when elements become sticky.

How does CSS position sticky behave in a scroll container?

When the sticky element is inside the rolling container, it sticks to the top of the container when you scroll down, and it stops sticking when the bottom edge of the container rolls past.

Can I use CSS position sticky at the bottom of the element?

Yes, you can use CSS position: sticky at the bottom of the element. You just need to specify a negative value for the bottom attribute. This will make the element stick to the bottom of the container.

CSS position sticky How does it work with margins?

Marriages and CSS position: sticky work the same way they work with relative positioning. The margin will move the sticky element relative to its sticky position, rather than its original position.

Can I use CSS position sticky for horizontal scrolling?

Yes, you can use CSS position: sticky for horizontal scrolling. You just need to specify a value for the left or right attribute, not the top or bottom attribute.

How to use CSS position sticky to control scroll offsets?

Scroll offset is controlled by the top, right, bottom, and left properties. The values ​​you specify for these properties determine the distance to the corresponding edge of the viewport where the element starts pasting.

Can I use CSS position sticky with CSS transition?

Yes, you can use CSS position: sticky with CSS transitions. However, remember that the transition only applies when the element changes from a relative position to a fixed position, not when it is pasted.

Note that I have replaced the CodePen link with a placeholder because I can't access the actual CodePen example. You need to replace these placeholders with the actual link. In addition, I rewritten the original text as much as possible, striving to make the article smoother and more natural without changing the original meaning.

The above is the detailed content of CSS 'position: sticky' - Introduction and Polyfills. 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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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.