JexSrs
JexSrs

Reputation: 155

html - fixed scroll header

Well such I searching to google for my anwser I found this for creating a fixed/sticky header on scroll. I want to make a change and this will work inside a div (div classes: w3-panel w3-card). .sticky class has top:0; and I am not sure how I will change this to be inside the div.

The code that I have is something like this:

The div I want to put all contents inside:

.cardDivInfo{
   width: 68.7%;
   min-width: 500px;
   float: left;
   margin-left: 16px;
   height: 505px;
   overflow-y: scroll;  
}

The anwser I found in W3Schools:(a little bit different):

   .header {
     padding: 10px 16px;
     background: #555;
     color: #f1f1f1;
   }
   .content {
     padding: 16px;
    }
    .sticky {
      position: fixed;
      top: 0;
      width: 100%;
    }
    .sticky + .content {
      padding-top: 102px;
    }

and html of course:

<div class="w3-panel w3-card-4 cardDivInfo">
  <div class="header" id="myHeader">
    <h2>Header Text</h2>
  </div>
  <div class="content">
    <p>Text with many words<p>
    <p>Text with many words<p>
    <p>Text with many words<p>
    <p>......</p>
  </div>
</div>

An the JavaScript:

    window.onscroll = function() {myFunction()};

var header = document.getElementById("myHeader");
var sticky = header.offsetTop;

function myFunction() {
  if (window.pageYOffset > sticky) {
    header.classList.add("sticky");
  } else {
    header.classList.remove("sticky");
  }
}

Upvotes: 0

Views: 93

Answers (1)

Jack Bashford
Jack Bashford

Reputation: 44087

What you want to do is just apply your sticky style to your element. Here's how I would make your #myHeader sticky:

#myHeader {
    position: sticky;
    top: 0;
 }

And just make sure that there is a <div> around it:

<div class="w3-panel w3-card-4 cardDivInfo">
    <div class="header" id="myHeader">...</div>
</div>

Upvotes: 1

Related Questions