position sticky polyfill with overflow support

11.1k views Asked by At

I am using position: sticky in my app, inside a container who use an overflow property to show a scrollbar. I have searched for a polyfill who does support this condition, but without any luck so far.

Does anyone know such a polyfill/shim who support oveflow ?

Regards

1

There are 1 answers

1
moritzjacobs On

I used a position: sticky polyfill called stickyfill to do this.

You just have to tell the polyfill to do it's job even on browsers that support position: sticky natively.

Here's a demo, also on Codepen

Stickyfill.forceSticky()
Stickyfill.add(document.querySelectorAll('[data-sticky]'));
body {
  padding: 50vh 2rem 100vh 2rem;
  font-size: 0.625rem;
  font-family: monospace;
  color: white;
}

.heading {
  display: flex;
}
.heading h2 {
  flex: 1;
  color: #444;
  font-weight: bold;
  padding: 1rem;
}

main {
  display: flex;
}

.parent {
  flex: 1;
  margin: 0 3px;
  padding: 1rem;
  display: flex;
  flex-flow: row nowrap;
  align-items: flex-start;
  overflow: visible;
}
.parent-sticky .sticky {
  position: -webkit-sticky;
  position: sticky;
}
.parent-overflow {
  height: 1000px;
  overflow: hidden;
}
.parent-worst .content, .parent-worst .sticky {
  background: linear-gradient(to bottom, tomato, red);
}
.parent-best .content, .parent-best .sticky {
  background: linear-gradient(to bottom, #11ee11, #22cc22);
  color: black;
}

.sticky {
  width: 50%;
  top: 1rem;
  margin-bottom: 1rem;
  padding: 0.3rem;
  background: linear-gradient(to bottom, #999, #555);
}

.content {
  flex: 1;
  height: 2500px;
  padding: 0.3rem;
  background: linear-gradient(to bottom, #999, #555);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stickyfill/2.1.0/stickyfill.min.js"></script>
<div class="heading">
 <h2>overflow: hidden;</h2>
 <h2>overflow: visible;</h2>
 <h2>overflow: visible;</h2>
 <h2>overflow: hidden;</h2>
</div>

<main>
 <div class="parent parent-sticky parent-overflow parent-worst">
  <div class="sticky">
   position: sticky native with overflow-hiding parent
  </div>
  <div class="content">
   doesn't work at all
  </div>
 </div>

 <div class="parent parent-sticky">
  <div class="sticky">
   position:sticky<br>native
  </div>
  <div class="content">
   Works fine in "newer" browsers
  </div>
 </div>

 <div class="parent parent-normal">
  <div class="sticky" data-sticky>
   stickyfill without overflow-hiding parent
  </div>
  <div class="content">
   works fine in most browsers
  </div>
 </div>

 <div class="parent parent-overflow parent-best">
  <div class="sticky" data-sticky>
   stickyfill with overflow-hiding parent
  </div>
  <div class="content">
   works fine in most browsers
  </div>
 </div>
</main>