avoid multiple sticky divs overlapping with each other with CSS only (no javascript)

Viewed 3255

I am trying to create something similar to the link below https://www.msn.com/en-gb/cars/news/this-barn-find-ferrari-just-sold-for-dollar13m/ss-BBMrCrE?li=BBoPWjQ

I have managed to create http://insurethe.000webhostapp.com/template.html so far.

I wanted the text "HEADING SPACE IN PAGE" to always remain on the top and always visible without scrolled away just like the msn search box.

I wanted the Sidebar not to overlap the text "HEADING SPACE IN PAGE" when scrolled.

And finally when I scroll and reach the text "HEADING SPACE IN PAGE must be still visible" I wanted the text "HEADING SPACE IN PAGE" to be still visible.

Also I do not know which CSS styles are needed and not needed to accomplish this task. I wanted to know what all CSS styles I can remove with out impacting the above mentioned behavior.

1 Answers

So to achieve what i think you are trying to do you just need to make some minor tweaks to your code.

Firstly you need to have the entire html under the same wrapper. So in your html you have two:

   <div class="wrapper cf"></div>

you need to remove the second one, and make the first one wrap the whole thing. Then you need to give sidebar a css command:

    .sidebar {
      top: 110px;
    }

Then remove

   .wrapper {
       margin-bottom:200px;
   }

as this will stop the sidebar overlapping when you get to the bottom of the page.

Here is a working example: https://codepen.io/FEARtheMoose/pen/QVEaOp?editors=1100

Let me know if this is now working how you want it to!

edit as per request:

add the second wrapper back in, and give sidebar z-index:-1;

edit 2: just remembered, you will also need to move the header

   <div style="position:sticky;top:0;background:white;height:100px;text-align:center;">
      <h1 style="color:orange">HEADING SPACE IN PAGE</h1>
      <strong style="color:red">Sidebar </strong>must be always below this line
      <hr>
   </div>

to in between the body tag and the first wrapper. see the codepen for updated code. [you will need to add css to put the width back how you wanted it however]

Related