Fake a Fix To Parent Element

Since position fixed is always relative to the viewport, we need to use clever absolute positioning to fix an element to its scrolling parent.

by abbylangner

HTML

<h2>Faking a Fix to Parent Element</h2>

<div class="wrapper">
  <div class="stuff">
    <p>An element with <code>position: fixed;</code> is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled:</p>
    <p>Therefore, if we need an element fixed to its scrolling <em>parent</em> instead of the viewport, we have to get clever with absolute positioning instead of fixed positioning.</p>
  </div>
  <div class="fixed">
  This div fakes fixed;
  </div>
</div>

CSS

div.wrapper{
  position: relative; /*context for absolute child*/
  background: #ffdfe5;
  width: 250px;
  height: 100px;
}
div.stuff{
  overflow: scroll;
  height: 100%; /*100% of parent == 100px above*/
}
div.fixed {
  position: absolute;
  bottom: 14px;
  right: 14px;
  width: 80px;
  border: 3px solid #73AD21;
}