Home >Web Front-end >CSS Tutorial >Why Isn't My Sticky Element Working Inside Its Parent Container?
You may encounter scenarios where position: sticky doesn't behave as expected when nested within another element.
The issue arises because position: sticky considers the parent element's size. If the parent element's height is determined by its sticky child, there's no space for the child to stick to.
Example:
.nav-wrapper { position: absolute; bottom: 0; } .nav-wrapper nav { position: sticky; top: 0; }
<div class="nav-wrapper"> <nav> <a href="#"><li>Home</li></a> <a href="#"><li>About</li></a> </nav> </div>
Adding a border to visualize the issue:
.nav-wrapper { position: absolute; bottom: 0; border: 2px solid; } .nav-wrapper nav { position: sticky; top: 0; } body { min-height:200vh; }
<div class="nav-wrapper"> <nav> <a href="#"> <li>Home</li> </a> <a href="#"> <li>About</li> </a> </nav> </div>
Solution:
To solve this, ensure that the parent element has its size independently defined, leaving space for the sticky child. This can be achieved using CSS properties like height or min-height.
The above is the detailed content of Why Isn't My Sticky Element Working Inside Its Parent Container?. For more information, please follow other related articles on the PHP Chinese website!