Search code examples
javascripthtmlcssparallax

Header Is Cutting Off Top Image During Parallax Scrolling


twintowersI've created a fixed header using JS on my site but that header is now cutting off the top of my first image. I am also using parallax scrolling. Here's my code:

Here's the HTML:

<head>
  <div class="header" id="myHeader">
    <h1>My Website</h1>
  </div>
</head>

<body>

  <div class="bgimg-1" ></div>

  <script src="./js/headerScroll.js">
  </script>
</body>

Now the JS (headerScroll.js):

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

let header = document.getElementById("myHeader");

let sticky = header.offsetTop;

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

Finally the CSS:


.header {
  padding: 10px 16px;
  background: white;
  color: black;
  border: 1px solid black;
}

.content {
  padding: 16px;
}

.sticky {
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 999;
}

.sticky+.content {
  padding-top: 102px;
}

body,
html {
  height: 100%;
  margin: 0;
  font: 400 15px/1.8 "Lato", sans-serif;
  color: #777;
}

.bgimg-1 {
  position: relative;
  opacity: 0.65;
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  background-image: url("../images/image1.jpg");
  min-height: 100%;
}

Is there anyway to move bgimg-1 lower so the header does not cut it off (or display the full image instead)?


Solution

  • Like this?

    window.onscroll = function() {
      myFunction()
    };
    
    let header = document.getElementById("myHeader");
    
    let sticky = header.offsetTop;
    
    function myFunction() {
      if (window.pageYOffset > sticky) {
        header.classList.add("sticky");
      } else {
        header.classList.remove("sticky");
      }
    }
    .header {
      padding: 10px 16px;
      background: white;
      color: black;
      border: 1px solid black;
    }
    
    .content {
      padding: 16px;
    }
    
    .sticky {
      position: fixed;
      top: 0;
      width: 100%;
      z-index: 999;
    }
    
    .sticky+.content {
      padding-top: 102px;
    }
    
    body,
    html {
      height: 100%;
      margin: 0;
      font: 400 15px/1.8 "Lato", sans-serif;
      color: #777;
    }
    
    .bgimg-1 {
      position: relative;
      opacity: 0.65;
      background-position: top;
      background-repeat: no-repeat;
      background-size: contain;
      background-image: url("https://www.howtogeek.com/wp-content/uploads/2019/08/img_5d5b215d04389.png");
      min-height: 100%;
    }
    <div class="header" id="myHeader">
      <h1>My Website</h1>
    </div>
    
    <div class="bgimg-1"></div>