'CSS Sticky sidebar and fixed header

I have a website with a sticky sidebar and fixed header

There's a problem when I start scrolling the pages, the sidebar is covered by the header

Here's pretty rough of js fiddle

Any way to fix this problem?

javascript solution is okay if there's no way to fix it with CSS

The only solution with javascript that I can think of is to check how far the user has been scrolled away, then add padding top to sidebar, something like this

let distance =  document.querySelector('.sidebar').getBoundingClientRect().top;

    if (distance <= 0 && viewport_width >= 768) {

        $('.sidebar').css('paddingTop', '150px');

    } else {

        $('.sidebar').css('paddingTop', '0px');

    }

Edit :

  • I want the z-index for header and sidebar to be the same
  • Both element should not be stacked against each other


Solution 1:[1]

Read this article for more details.

.sidebar {
  width: 25%;
  height: 25vh;
  min-height: 200px;
  overflow: auto;
  position: sticky;
  top: 5%;
}

.main {
  width: 60%;
  height: 200vh;
  min-height: 1000px;
  display: flex;
  flex-direction: column;
}

.main,
.sidebar {
  border: 5px solid #222;
  background-color: white;
  border-radius: 10px;
  color: #222;
  padding: 15px;
}

.wrapper {
  display: flex;
  justify-content: space-between;
}

body {
  padding: 3%;
  background-color: #ccc;
  font-size: 20px;
  box-sizing: border-box;
  font-family: Lato, sans-serif;
}

code,
pre {
  background-color: #ccc;
  padding: 0 3px;
  border-radius: 5px;
}

.bottom {
  justify-self: bottom;
}
<div id="header">
  <h2>Header</h2>
  <p>This is the header blab al alb albalblablabla lb lab labl abl labl ablalbalbla blaba lb lablablablablalba balb lab alb alb la</p>
</div>
<div class="wrapper">
  <div class="main">
    <h2>Main content</h2>
    <p>Scroll down the page!</p>
    <h3>How to recreate this</h3>
    <p>
      Position the columns with flex. Then apply two lines of CSS to the sidebar to make it sticky:
      <pre>
.sidebar {
  position: sticky;
  top: 0;
}
    </pre> Include <code>position: -webkit-sticky;</code> for Safari.
    </p>
  </div>

  <div class="sidebar">
    <h3>Sticky sidebar</h3>
    <p>I will follow you!</p>
    <p><a href="https://caniuse.com/#search=sticky">caniuse stats</a>
  </div>
</div>
<div id="footer">
  <h2>Footer</h2>
  <p>This is the footer</p>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nikkkshit