1

I need a sticky header relative to parent div. Currently, Header is sticky only on a section div. But I want a sticky header relative to a parent class.

HTML code

<div class="parent">
   <div class="section-one">
      <h1>Header 1</h1>
      <div class="content">
         content 123
      </div>
   </div>
   <div class="section-two">
      <h1>Header 2</h1>
      <div class="content">
         content 789
      </div>
   </div>
   <div class="section-three">
      <h1>Header 3</h1>
      <div class="content">
         content 456
      </div>
   </div>
</div>

Here is my css,

.parent {
   position: relative;
}
.section-one h1{
   position: sticky;
   top: 0;
   z-index: 9999;
}
.section-two h1{
   position: sticky;
   top: 50;
   z-index: 9999;
}
.section-three h1{
   position: sticky;
   top: 100;
   z-index: 9999;
}

I want a sticky header as per below

Header 1
Header 2
Header 3

I want a sticky header as per image. I want this type of sticky header

Manoj Ghediya
  • 547
  • 1
  • 7
  • 19

1 Answers1

0

$(window).scroll(function() {
    var distanceFromTop = $(this).scrollTop();
    if (distanceFromTop >= $('.section-one').offset().top) {
        $('.section-one h1').addClass('fixed');
    }
    if (distanceFromTop >= $('.section-two').offset().top) {
        $('.section-two h1').addClass('fixed');
    }
    if (distanceFromTop >= $('.section-three').offset().top) {
        $('.section-three h1').addClass('fixed');
    }


    if (distanceFromTop >= $('.parent').height()) {
        $('.section-one h1').removeClass('fixed');
        $('.section-two h1').removeClass('fixed');
        $('.section-three h1').removeClass('fixed');
    }
});
.parent {
   position: relative;
}
.section-one, 
.section-two, 
.section-three { min-height: 100vh; }

.section-one { background: lightgray; }
.section-two { background: lightblue; }
.section-three { background: lightgreen; }

.section-one h1{
   position: sticky;
   top: 0;
   z-index: 9999;
}
.section-two h1{
   position: sticky;
   top: 0;
   z-index: 9999;
}
.section-three h1{
   position: sticky;
   top: 0;
   z-index: 9999;
}


.section-one h1.fixed {
    position: fixed;
    top: 0px;
}
.section-two h1.fixed {
    position: fixed;
    top: 50px;
}
.section-three h1.fixed {
    position: fixed;
    top: 100px;
}
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<div class="parent">
   <div class="section-one">
      <h1>Header 1</h1>
      <div class="content">
         content 123
      </div>
   </div>
   <div class="section-two">
      <h1>Header 2</h1>
      <div class="content">
         content 789
      </div>
   </div>
   <div class="section-three">
      <h1>Header 3</h1>
      <div class="content">
         content 456
      </div>
   </div>
</div>
<div style="height: 100vh; background: green;"></div>