CSS - Relative to Fixed transistion

using css and javascript

by Ben Clayton

HTML

<body>
  <div class="front">
    <h1>Front matter</h1> The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.
  </div>

  <div id="content-anchor"></div>
  <div id="sticky-phantom"></div>
  <div id="sticky"><div id="sticky-text">This turns sticky</div></div>

  <div class="main">
    <h1>Main document</h1> The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.
  </div>

</body>

CSS

h1 {
  margin: 0px;
  padding: 5px;
}

.front {
  background: #d0d0ff;
  height: 200px;
  width: 100vw;
  padding: 5px;
}

.main {
  background: #d0ffd0;
  height: 1000px;
  width: 100vw;
  padding: 5px;
}

#sticky {
  background: #000000;
  color: #ffffff;
  font-size: 30px;
  text-align: center;
  width: 98.1vw;
  opacity: 0.8;
  height:35px;
  transition:height 1s;
}

#sticky-text {
  transition:transform 1s;
  transform-origin:top;
  transform:scale(1,1);
}


#sticky-phantom {
  background: #000000;
  color: #ffffff;
  font-size: 30px;
  text-align: center;
  width: 100vw;
  display: none;
}

#sticky.stick {
  position: fixed;
  top: 0;
  width: 100%;
  height:20px;

}
.stick #sticky-text {
  transform:scale(0.5,0.5);
}

JavaScript

function sticky_relocate() {
  var window_top = $(window).scrollTop();
  var div_top = $('#content-anchor').offset().top;
  if (window_top > div_top) {
    $('#sticky').addClass('stick');
    $('#sticky-phantom').show();
  } else {
    $('#sticky').removeClass('stick');
    $('#sticky-phantom').hide();
  }
}

$(function() {
  $(window).scroll(sticky_relocate);
  sticky_relocate();
});