Sticky Position does not Work with Grid/Flex parent

Frontend developers, do you ever experience strange behavior from sticky elements in your code? I surely did, until I learned that sticky positioning does not work correctly when direct parent elements are flex or grid. To some of you this may already be obvious, somehow I managed to have years of frontend experience before figuring this out.

Problem

Imagine a sidebar menu that needs to 'stick' to the left side of the page. So as the user is scrolling through the content of the page, the menu always remains to the side for easy access. This is a common feature for sites with many pages and lots of content (blogs, documentation, ecommerce stores etc.).

Let's use this code as our example:

<div className='grid grid-cols-5'>
  <Menu className='sticky top-0 col-span-1'/>
  <PageContent className='col-span-4'/>
</div>

Using react and tailwind, but works the same for any js/css config

See we have a sticky element with a direct grid parent. The grid layout will work completely fine, yet the sticky positioning will not!

Solution

The simplest way to fix this issue and keep your grid / flex layout, is to wrap the sticky component in an additional div.

<div className='grid grid-cols-5'>
  <div className='col-span-1'>
    <Menu className='sticky top-0'/>
  </div>
  <PageContent className='col-span-4'/>
</div>

Super simple! Just make sure you move the flex/grid styles to this new div. Now, you can use both flex/grid with sticky positioning.