position sticky automatic "top" position
Asked Answered
D

1

11

Is there a way for stickies to take into account other stickes on the page?

For example:

body {
  display: flex;
  min-height: 2000px;
  flex-direction: column;
}
#header {
  height: 40px;
  flex: 0 0 auto;
  position: sticky;
  top: 0;
  background: yellow;
}
#footer {
  flex: 0 0 auto;
  height: 20px;
}
#main {
  display: flex;
  flex: auto;
  background: blue;
}
#side {
  width: 200px;
  background: red;
}
#side > div {
  position: sticky;
  top: 0px;
}
<div id="header">header</div>
<div id="main">
  <div id="side">
    <div>side</div>
  </div>
  <div id="content">
    content
  </div>
</div>
<div id="footer">footer</div>

Notice that if I scroll down the header will overlap the sidebar because they have the same top position.

To fix I have to make the top position of the sidebar take the value of the header height

body {
  display: flex;
  min-height: 2000px;
  flex-direction: column;
}
#header {
  height: 40px;
  flex: 0 0 auto;
  position: sticky;
  top: 0;
  background: yellow;
}
#footer {
  flex: 0 0 auto;
  height: 20px;
}
#main {
  display: flex;
  flex: auto;
  background: blue;
}
#side {
  width: 200px;
  background: red;
}
#side > div {
  position: sticky;
  top: 40px;
}
<div id="header">header</div>
<div id="main">
  <div id="side">
    <div>side</div>
  </div>
  <div id="content">
    content
  </div>
</div>
<div id="footer">footer</div>

But what if the header has variable height? Can I tell the browser somehow to position the stickies so they dont overlap others?

Disconsider answered 3/3, 2015 at 18:43 Comment(1)
hi, I am facing the same issue in 2021, did you find an answer for this? basically I don't want to use js to update the top value of a dynamic headerJoleenjolene
M
1

I think you would need to use javascript for this. First to get the height of the header and then set the top position of your side div using that value. I am not aware of any pure css way of doing it I am afraid.

If you are using jQuery it is simply using the .height() method if not you can use this:

var clientHeight =        document.getElementById('myDiv').clientHeight;

var offsetHeight = document.getElementById('myDiv').offsetHeight;

The offset method gets the height with any padding and borders.

Monomolecular answered 3/3, 2015 at 19:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.