April 15, 2015

Fixed header on scroll

Fixed header on scroll

You need some JS to do scroll events. When scrolling goes to a certain point the header gets fixed.

HTML

<header class="header"><span>Header</span></header>
<main class="contents">
  <h1>Scroll Fixed Header</h1>
  <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ullam beatae in officia totam tempore, neque, reiciendis inventore. Modi dolore maxime, fugiat, minus ad doloremque perspiciatis placeat quos odit assumenda voluptas!  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus delectus recusandae odit nostrum beatae incidunt reprehenderit, enim excepturi optio veniam velit architecto, dolores, dolor quia necessitatibus quod ducimus est. A.  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque iusto aut inventore eum aliquid laudantium modi ad impedit. Sit mollitia cupiditate nulla est magni dignissimos iure laborum enim asperiores nostrum.</p>
</main>

CSS

body {
  font-family: "arial", sans-serif;
}

main {
  font-size: 1.25rem;
  line-height: 1.7;
}

.header {
  -webkit-transition: all 0.3s ease-in;
  -moz-transition: all 0.3s ease-in;
  transition: all 0.3s ease-in;
  position: fixed;
  top: 0;
  left: 0;
  height: 180px;
  width: 100%;
  padding: 0 5%;
  margin-top: 50px;
  background-color: #98c;
  line-height: 180px;
  z-index: 500;
  font-size: 2rem;
  color: #fff;
  font-weight: bold;
}
.header.active {
  height: 50px;
  line-height: 50px;
  font-size: 1.25rem;
}

.contents {
  padding: 0 5%;
  margin: 220px auto;
  min-height: 700px;
}
.contents h1 {
  font-size: 2.75rem;
  line-height: 1.2;
  margin-bottom: 25px;
  font-weight: bold;
  color: #98c;
}
.contents p {
  color: #fff;
}

jQuery

$(window).on("scroll",function(){
  if($(this).scrollTop() >= 60) {
    $(".header").addClass("active");
  } else {
    $(".header").removeClass("active");
  }
});
demo

No comments:

Post a Comment

Popular Posts

Views