How to Make CSS Position Sticky: Tutorial With Examples

Aakash Rao

Posted On: January 18, 2024

view count387377 Views

Read time24 Min Read

Have you ever come across the famous saying, The journey is just as important as the destination? This saying holds a profound truth in the world of web development. As the digital world evolves, it becomes crucial to ensure that the website is not merely a destination but also a delightful journey, emphasizing the importance of the entire user experience.

Crafting an engaging and dynamic interface is not just a matter of choice but a fundamental necessity. In this evolving landscape, where every scroll and click weaves a narrative, the significance of CSS position: sticky, emerges as a crucial property.

This feature can significantly enhance user experience and engagement from a business standpoint, contributing to the website’s more polished and professional appearance. Additionally, it keeps important information on the screen at all times, increasing the click-through rate (CTR) on those links.

In this blog about CSS position: sticky, we will explore the potential of sticky positioning in modern web design, step-by-step, with real-world examples.

We will also learn about accessibility with WCAG guidelines and best practices when implementing sticky elements to make sticky elements accessible, ensuring that the website remains inclusive and user-friendly for all.

Understanding the Role of CSS position: sticky

CSS position: sticky is a property that gives a simple way to control the position of an element as we scroll down a page.

It allows developers to set the rules for stickiness by defining a point – it could be the top or bottom. When the user scrolls to that point, the element becomes sticky and stays fixed in that position until we scroll past it. This is particularly useful when we want things to move with the flow of the page but also stick around when needed.

Case of CSS position

Sticky Sidebar Use Case of CSS position: sticky

The above output is shown on the LT Browser.

LT Browser is a dev-friendly browser built on Chromium that helps developers and testers test websites for responsiveness across various device viewports. It offers a comprehensive, responsive testing environment with over 50 pre-installed viewports, including mobile, tablet, desktop, and laptop.

We will also use LT Browser to render outputs for other examples in upcoming sections.

Some real-world use cases of position sticky include navigation menu bars, sticky sidebars, table headers, and advertisement or alert banner components that must remain visible as users scroll through content. Let’s explore the behavior of position: sticky with an example.

HTML:

CSS:

Preview:

This example shows the default behavior of CSS position: sticky. The top: 0 sets the sticky element to stick to the top edge of its containing block (which is the nearest scrolling ancestor).

See the Pen
Sticky Element Example with position: sticky
by Aakash Rao (@aakash_codes)
on CodePen.

Why Use CSS position: sticky?

CSS position: sticky is a powerful way to create sticky element behavior on a webpage. It has become the standard approach due to its simplicity and efficiency, while JavaScript offers an alternative method for developers to achieve the same sticky element effect.

CSS native solution is often preferred for several reasons. Firstly, using CSS for sticky positioning is more straightforward and requires less code than the JavaScript alternative.

Using JavaScript, we leverage scroll event handlers to track the page’s offset. By dynamically calculating these offsets, we can implement logic that triggers the element to become sticky once a specific threshold is reached by the user. Let’s try to implement this and explore the behavior in action.

HTML:

CSS:

JavaScript:

Preview:

See the Pen
Sticky Element Example with position: sticky
by Aakash Rao (@aakash_codes)
on CodePen.

The disadvantage of using JavaScript scroll handling is it leads to performance issues, especially on mobile devices. Another problem it brings is scroll jank, which is noticeable from the above example and refers to a disjointed or stuttered scrolling experience. This can be especially noticeable during rapid scrolling on less powerful mobile devices.

Additionally, if any user has JavaScript disabled or has errors in the JavaScript code, the sticky behavior will not work. Meanwhile, relying on CSS brings more efficiency. This is why websites implementing a sticky element through JavaScript may experience quicker UI degradation than those using CSS.

Is CSS position: sticky Frequently Used?

Yes, the CSS position: sticky is commonly used when we want to set an element to stick at a particular position for a while and then acts like a normal element in most cases, flowing with the document’s layout.

Talking about its usage—it depends on what the website needs. If you have a long page with lots of content, having a sticky navigation bar can make it easy for users to access important links without scrolling all the way back up. It’s also handy for elements like headers or sidebars you want to keep visible while users explore the content.

However, not every website needs a sticky element. Some designs may work better without sticking elements, and that’s perfectly fine. It’s about finding the balance between functionality and aesthetics, tailoring the use of CSS position: sticky to enhance the user experience without unnecessary additions.

So, in a nutshell, CSS position: sticky is a useful property, but its frequency of use depends on each website’s specific needs and style.

Differences: CSS position: sticky vs position: fixed

Both the position: sticky and position: fixed are CSS positioning properties commonly used in web development for creating layouts and UI designs for making elements stick on the webpage.

While they may appear similar initially, a closer look reveals important differences in how they operate, each serving a distinct role in creating visually appealing and functional websites.

Let’s dive into the details of each with an example, discussing their roles, use cases, and how CSS position: sticky can be considered a better option in certain scenarios.

HTML:

CSS:

Preview:

In the first container, we have a fixed element with the .fixed class. The CSS rule .fixed applies for position: fixed to this box, meaning it stays fixed in its position regardless of scrolling. While in the second container, we’ve got a sticky element with the .sticky class. The CSS rule .sticky applies for the position: sticky and sets top: 0.

From the above example, we can highlight some key differences:

CSS position: sticky CSS position: fixed
Initially part of the normal viewport flow. Remains fixed relative to the viewport.
Sticks when it reaches the top of its container during scrolling. Overlaps other content in the container.
Interacts with the flow of other elements until it becomes sticky. It doesn't interact with the flow of other elements.

These behaviors showcase the fundamental differences between position: fixed and position: sticky and demonstrate how each can be applied to create distinct effects in a web page layout.

When to Use CSS position: sticky over position: fixed?

CSS position: sticky is ideal when you want an element to be temporarily fixed within a container but still be part of the document flow. It’s useful when you want a header, sidebar, or other call-to-action (CTA) element to stay visible during scrolling but not necessarily fixed to the entire viewport.

CTA: Position Sticky on Desktop and Position Fixed on Mobile

CSS position: fixed can be used in scenarios such as when an element needs to be fixed relative to the viewport, regardless of its parent container’s scrolling. It’s ideal for things like navigation bars you want visible at all times, no matter how much the user scrolls. And when the element shouldn’t be affected by the scrolling of its parent container.

The only disadvantage with CSS position: fixed is that it can lead to issues on smaller screens or in responsive designs, as the fixed position covers the content area of the viewport.

Practical Examples With CSS position: sticky

Now that we’ve understood the fundamentals of CSS position: sticky, let’s dive into some real-world examples to see it in action and explore its applications.

Sticky Navigation Bar

A sticky navigation bar, sometimes also called a sticky header, is a common web design feature where the navigation menu remains visible at the top of the page, even as the user scrolls down.

This helps to enhance the user experience by providing easy access to navigation options without the need to scroll back to the top of the page. To create a sticky navigation bar, we can use the CSS position: sticky property, along with defining the top value.

HTML:

CSS:

Preview:

See the Pen
Sticky Navigation Bar Example
by Aakash Rao (@aakash_codes)
on CodePen.

A very good use-case of a sticky navigation bar is to display the progress of the scroll as users navigate through a webpage. Using a progress bar beneath the sticky navigation gives the user a visual indicator of their position within the content.

This feature can be used in blogs to enhance the overall user experience of readers by offering real-time feedback on how much content has been scrolled through and how much remains, facilitating easier navigation and providing a sense of context within the webpage.

We can implement this by adding a few lines of code to our sticky navigation bar example.

HTML:

CSS:

JavaScript:

Preview:

We can notice as users scroll, the progress bar dynamically updates, offering a clear and intuitive representation of the user journey through the content and helps in navigation efficiency.

See the Pen
Sticky Navigation Bar with Scroll Progress
by Aakash Rao (@aakash_codes)
on CodePen.

Sticky Sidebar

A sticky sidebar is another common web design feature where a sidebar on a webpage remains fixed or “sticky” as the user scrolls down the page. This is particularly useful for long pages where the sidebar contains important navigation links or information that should remain easily accessible.

property

Example of Sticky Sidebar on LambdaTest Learning Hub

To create a sticky sidebar, we can use the CSS position: sticky property along with defining the top, similar to the approach used for a sticky navigation bar.

HTML:

CSS:

JavaScript:

Preview:

See the Pen
Sticky Sidebar Example
by Aakash Rao (@aakash_codes)
on CodePen.

In this example, we can notice that the sidebar of categories for blogs is positioned with sticky to be accessible to readers as they scroll to the bottom of the page. This is a very common use-case of CSS position: sticky, and you will find it in almost all the content-rich websites for a sidebar for showing ad banners, advertisements, or CTAs.

As for the sticky navigation bar example, feel free to customize the styles and structure to fit the specific design needs. The key is to use the CSS position: sticky property to make the sidebar stick to a specified point on the page.

To access the code for the posts example, refer to this GitHub Repository.

Sticky Footers

A sticky footer is a design feature where the footer of a webpage remains fixed at the bottom of the viewport, regardless of the content’s height.

This is useful for creating a consistent layout, especially on web pages with dynamic content. Creating a sticky footer involves combining CSS properties to achieve the desired effect. Let’s learn how to build a sticky footer in CSS with an example.

HTML:

CSS:

This example ensures that the footer remains at the bottom of the viewport, and the main content pushes it down if it extends beyond the viewport height.

See the Pen
Sticky Footer Example
by Aakash Rao (@aakash_codes)
on CodePen.

Although this is a standard way of making a sticky footer, we can create a cool effect with a revealing footer by just adding z-index: -1, which will make the footer reveal as we reach the bottom. Let’s see this in action.

For this example, we’ve added max-width and margin-inline: auto to center it and adjusted it with the main container.

Sticky Table Headers

A sticky table header is a design technique that keeps the header of a table fixed at the top of the viewport while the rest of the table content can be scrolled.

This is particularly useful when dealing with tables that have a large number of rows, allowing users to view column headers even as they scroll through the data.

Let’s create a sticky table header and see how CSS position: sticky works with an example.

HTML:

CSS:

In this example, the .form-header-sticky class represents the styling for the form header to make it sticky. The position: sticky property is applied, and top: 0 ensures that the header remains at the top of the table.

See the Pen
Sticky Table Header Example
by Aakash Rao (@aakash_codes)
on CodePen.

Scrollytelling With CSS position: sticky

We’ve already covered some basic yet important use cases of CSS position: sticky. However, the position: sticky property can also be used creatively for storytelling with modern CSS.

This involves creating an engaging and interactive narrative on a webpage. We can use earlier techniques, such as revealing hidden elements and sticky images with sidebars. Let’s understand how we can build this with an example.

HTML:

CSS:

This example shows how creatively we can apply position: sticky to create an engaging and dynamic storytelling experience, guiding users through the narrative with visual and navigational elements that respond to their scrolling behavior.

Precedence in CSS position: sticky

As we built different real-world examples from the previous section, we saw that we could apply position: sticky for either top or bottom property. But now the question arises: what will happen if both top and bottom values are defined for a sticky element? Which one will take precedence for CSS position: sticky?

When CSS sticky encounters conflicting threshold values, it adheres to a precedence rule to prioritize one over the other. The rule works as follows:

  • If the developer sets both top and bottom values, the top value takes precedence.
  • When the developer specifies both left and right values:
    • If the specified direction is left to right (LTR), the left value wins.
    • If the specified direction is right to left (RTL), the right value wins.

These guidelines ensure that conflicting values are resolved in a consistent manner, giving preference to specific directions based on the developer’s specifications. Note that the direction mentioned above refers to writing direction. For example, Arabic is RTL (right to left), while English is LTR (left to right).

You can check out an article on CSS Writing Modes to learn more about the details of different writing directions and how it works.

When working with CSS position: sticky, developers often face a few issues. We will discuss these issues and their fixes in the next section.

How to Fix Issues With CSS position: sticky Not Working

CSS position: sticky is undoubtedly a valuable property to make any element stick. However, many beginners made mistakes while implementing it into CSS, leading to issues with CSS position: sticky not working properly.

A common issue is when a child element has the same height and width as its parent element. This gives the child element no room, keeping it in the same position.

See the Pen
Common Issue with CSS Position Sticky
by Aakash Rao (@aakash_codes)
on CodePen.

As we can notice, the < div > element with class .sticky is wrapped inside an < div > element, which by default tries to take the same height and weight of its child to wrap, meanwhile making the sticky position not work as we want.

See the Pen
[Fixed]: Common Issue with CSS Position Sticky
by Aakash Rao (@aakash_codes)
on CodePen.

To fix this, we need to make the child element have a width and height less than its immediate parent to make it stick to move within the parent container. Another way to solve this issue can be by defining a fixed width and height (greater than the child) to the parent < div > of the sticky element. Doing so gives room for sticky elements to stick to their position inside the parent.

Browser Compatibility Support for CSS position: sticky

The adoption of position: sticky is not just a matter of trend; it’s about enhancing functionality and accessibility.

Sticky elements offer a smoother navigation experience, reducing the need for users to scroll back to access critical information instantly. This improves user satisfaction and can positively impact business metrics such as reduced bounce rates, longer session durations, and increased click-through rates.

Browser Compatibility Support for CSS position sticky

Source

And for the browser support of CSS position: sticky, it is supported by all major browsers as per CanIUse, allowing developers to use its power whenever they want.

Info Note

Test your websites for CSS position: sticky across 3000+ environments. Try LambdaTest Today!

Why Does overflow: hidden Prevent position: sticky From Working?

Another big issue many developers encounter when implementing CSS position: sticky is when overflow: hidden is set to the parent element of the sticky element.

When we use position: sticky on an element, we tell the browser to make an element stick to a specific position on the page when the user scrolls. However, for this to work, the browser needs to know where to stick it, and it usually looks for the nearest ancestor (parent) with a scrolling ability (like a scrollbar).

The position: sticky property relies on the scroll behavior of the document to trigger its sticky behavior. If an ancestor element of a sticky element has overflow: hidden, it can interfere with the scroll behavior and cause the sticky element not to stick properly.

This is because the ancestor element with overflow: hidden effectively hides the overflow content, and this can disrupt the normal scroll flow that position: sticky relies on.

See the Pen
The overflow:hidden preventing position:sticky from working
by Aakash Rao (@aakash_codes)
on CodePen.

ChatGPT With Sidebar having a Sticky Element on Top

ChatGPT With Sidebar having a Sticky Element on Top

In the example, the sidebar contains a sticky element. The overflow: hidden on the sidebar, is used to limit its height. However, this can interfere with the sticky positioning of the element inside. As you scroll down, you may notice that the sticky element logo doesn’t stay in its intended position due to the overflow: hidden property on the sidebar.

sidebar contains a sticky element

Source

To fix this problem, we can use the overflow: clip property. This property is similar to overflow: hidden, which hides extra content but with a slight difference. The hidden value allows programmatic scrolling and creates a new block formatting context (BFC). At the same time, the clip completely disables any kind of scrolling and doesn’t establish a new block formatting context.

See the Pen
[Fixed]: overflow:hidden preventing position:sticky from working
by Aakash Rao (@aakash_codes)
on CodePen.

For an element with position: sticky to work correctly, it must be within a BFC. Setting overflow: hidden on a parent element creates a BFC, but it also prevents any elements inside from sticking to it, as they’re confined to that BFC.

So, when you use overflow: clip, it hides overflowing content just like hidden, but it doesn’t turn the element into a scroll container. In other words, it doesn’t allow the element to scroll programmatically. The window, or viewport, remains the default scroll container.

To put it simply, if you want to hide extra content without allowing any scrolling, use overflow: clip. This ensures that the window remains the main scroll area, and the element won’t become a scroll container.

Best Practices for Sticky Navigation Menu Element

Sticky positioned elements, such as sticky navigation menus, can enhance the user experience by providing persistent navigation or content that remains visible as the user scrolls.

However, they can also introduce potential accessibility challenges. Let’s learn about some accessibility issues associated with sticky navigation menus or headers and how we can tackle them using simple best practices.

  • Browser Compatibility and Accessibility Testing: Performing cross browser and accessibility testing of CSS position: sticky is important for ensuring a consistent and user-friendly experience across different browsers and for users with various accessibility needs.
  • So make sure to test your elements for accessibility and perform cross browser testing. For scalability and reliability, you can leverage cloud-based testing like LambdaTest. It is an AI-powered test orchestration and execution platform that lets you test websites for CSS position: sticky on an online browser farm on over 3000+ browsers and operating systems.

    Looking to get started with LambdaTest? Check out the tutorial below on performing real-time testing on LambdaTest.

    Subscribe to the LambdaTest YouTube Channel for the latest tutorials on mobile app testing, real device cloud, and more.

  • Considering Content-to-Chrome Ratio: Sticky headers take up screen space that could be used for content. It’s crucial to use that space wisely. This is especially important on smaller screens like mobile devices.
  • Aim for a good balance between content and the header size, ensuring text is readable, and tap targets are at least 1cm × 1cm on touchscreens. While there’s more space for desktops, avoid unnecessary header height and prioritize readable text sizes over excessive empty pixels, even for logos.

    Considering Content-to-Chrome Ratio

    Source

    For touchscreens, it’s a good idea to make buttons or things you tap on as big as a small coin, like a quarter. The words should be the size you see on your phone, not too tiny. Also, try to keep everything a good size so it looks nice but not too tall. This way, it’s easier for people to use it on their phones.

  • Ensuring Good Contrast Ratio: Another big issue arises when there is not enough contrast between the sticky navigation menu and the page’s content area.
  • Ensuring Good Contrast Ratio

    Source

    This example demonstrates a problem – the navigation submenu doesn’t stand out well from the content area. This leads to failure to meet the requirements of Success Criterion 2.4.11 Focus Appearance, which suggests having a contrast ratio of at least 3:1 between the focused and unfocused states, ensuring better visibility and user experience.

    We must also ensure that focusable elements remain visible with a sticky menu. This also goes for internal page anchors that need to account for the sticky bar using the scroll-padding property in CSS to unobscure content adhering to the W3C technique.

    elements remain visible with a sticky menu

    LambdaTest Menu

    The above examples show a good contrast difference with the content area using box-shadow on the bottom.

    While deciding the color for a sticky header on a website, we can ensure it looks different from the rest of the page. This can be done either with a different contrasting color or by applying a box shadow that highlights the current active state of the user.

  • Building Partially Persistent Headers: Partially persistent headers, often found on mobile sites, strike a balance between accessibility and non-intrusiveness during scrolling. When you scroll up, the header usually appears, thinking you want to use it. It gets hidden as you start scrolling towards the bottom.
  • The above example shows the partially persistent header example for mobile screens on the Lenskart website.

    To enhance the user experience, developers can opt for subtle animation. Implementing a gradual reveal as the user scrolls up slightly ensures a smooth transition. Aim for a 300–400 milliseconds slide animation, balancing user-friendly functionality and minimal disruption.

  • Consider Whether a Sticky Element is Needed at All: As mentioned earlier, sacrificing some screen space on every page may not be beneficial. If the sticky header doesn’t add user value, design improvements are pointless.
  • For example, will users log in on different pages if the header has a login button? Will users switch between categories or stay in one if it includes main navigation? The answers depend on the website type, tasks, and content.

Wrapping Up

To wrap it up, diving into CSS position: sticky allows developers to create awesome, user-friendly websites. We started by understanding the basics and seeing how CSS position: sticky is special and handy compared to its buddy CSS position fixed.

We explored some real-world examples and tried to build them from scratch. We also discussed the accessibility of the sticky navigation menu, sharing the best ways to handle it. We also learned about its browser support and compatibility across different browsers.

Frequently Asked Questions (FAQs)

Are there any performance considerations with CSS position: sticky?

While CSS position: sticky is generally performant, excessive use of sticky elements may impact the performance of web pages. Always try to test the design across various devices to monitor performance.

Can I use the CSS position: sticky on mobile devices?

Yes, CSS position: sticky works on mobile devices. However, it’s crucial to test and optimize the design for responsiveness on various screen sizes to ensure a consistent user experience.

Are there any alternatives to CSS position: sticky?

Yes, alternatives include using JavaScript or APIs like Intersection Observer for sticky behavior. However, the CSS position: sticky is preferred for its simplicity and performance.

Can I use the CSS position: sticky on table elements?

Yes, CSS position: sticky can be applied to table elements such as table headers, making headers stick while scrolling through a large table.

Author Profile Author Profile Author Profile

Author’s Profile

Aakash Rao

I am a Frontend Developer and Technical Writer based out of India who loves to create and share knowledge on Twitter with the community. I am a community guy who loves to connect and interact with fellow developers and enthusiasts. Alongside, I love to listen to podcasts and read books with a keen passion to explore other fields such as Graphic design & VFX.

Blogs: 6



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free