1

I'm trying to make an interface where two parts overlap, and one can scroll through the first part horizontally and the second part vertically. I quickly discovered the css sticky position.

Here is code demonstrating the issue I encountered using position: sticky; :

body {
  margin: 0;
}

#d1 {
  background: red;
  position: sticky;
  top: 0;
  width: 2000px;
  height: 50px;
  opacity: 0.8;
}

#d2 {
  background: blue;
  position: sticky;
  left: 0;
  width: 50px;
  height: 2000px;
  opacity: 0.8;
}
<div id="d1"></div>
<div id="d2"></div>

(doesn't work in my browser, here is a jsfiddle https://jsfiddle.net/2bovgy84/1/ )

If you scroll down red div stays on top (what I expect), but if you scroll right blue div gets "stuck" half-way through (but I expect it to behave like the red one does)

I do not understand this behavior, at all.

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Dragorn421
  • 174
  • 12

2 Answers2

2

body needs to be allowed to grow wider than HTML/window's width so it doesn't drag the blue element along with it (backgrounds on html/body shows what happens : https://jsfiddle.net/Lq473pue/1/ ).

you can use for that:

  • display:inline-block;

  • display:table;

  • float:left;

jsfiddle updated : https://jsfiddle.net/Lq473pue/

min-width:100%; can also be handy for body

G-Cyrillus
  • 101,410
  • 14
  • 105
  • 129
1

The body needs the width or you need elements that are not sticky to create that width. Otherwise your body will be the width of the viewport.

https://jsfiddle.net/y9r74c0x/20/

body {
  margin: 0;
  width: 2000px;
}

#d1 {
  background: red;
  position: sticky;
  bottom: 0;
  width: 2000px;
  height: 50px;
  opacity: 0.8;
}

#d2 {
  background: blue;
  position: sticky;
  right: 0;
  width: 50px;
  height: 2000px;
  opacity: 0.8;
}
<div id="d1"></div>
<div id="d2"></div>
Kevin Choppin
  • 375
  • 1
  • 8