Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

position sticky automatic "top" position

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?

like image 926
Elfy Avatar asked Mar 03 '15 18:03

Elfy


1 Answers

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.

like image 57
Steven Hoskins Avatar answered Oct 11 '22 10:10

Steven Hoskins