Skip to content

Instantly share code, notes, and snippets.

@DevTarakanova
Created October 27, 2018 14:00
Show Gist options
  • Save DevTarakanova/1d5447a252ad402b6aca194af03f9f4e to your computer and use it in GitHub Desktop.
Save DevTarakanova/1d5447a252ad402b6aca194af03f9f4e to your computer and use it in GitHub Desktop.
Sticky Header
.sticky {
position: fixed;
top: 0;
width: 100%;
}
.sticky + .content {
padding-top: 102px;
}
<div class="header" id="header">
<h2>My Header</h2>
</div>
<div class="content">
<h3>On Scroll Sticky Header</h3>
<p>The header will stick to the top when you reach its scroll position.</p>
<p>Scroll back up to remove the sticky effect.</p>
</div>
<script>
window.onscroll = function() {myFunction()};
var header = document.getElementById("header");
var sticky = header.offsetTop;
function myFunction() {
if (window.pageYOffset > sticky) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment