0

I created this piece of code containing a gold container that scrolls vertically. On top on it there is another container that should be always visible.

I tried using position absolute and sticky but I don't understand why it is not in the right position.

When I scroll down, it should be visibile always on top...

<div style="border: 1px solid black;">
  <div
    style="position: relative; height: 500px; max-height: 500px; overflow-y: auto;"
  >
    <div style="width:100%; height: 500px;">
      <svg x="0" y="0" width="100%" height="800">
        <rect x="0" y="0" width="100%" height="800" fill="gold"></rect>
      </svg>
    </div>

    <div
      style="position: absolute; top: 0; width: 100%; height: 112px; background-color: rgba(0, 0, 0, 0.2);"
    >
      <div
        style="width: fit-content; padding: 15px; color: white; border: 1px solid white; margin: 20px 10px;"
      >
        Button text
      </div>
    </div>
  </div>
</div> 
whitecircle
  • 237
  • 9
  • 34
  • Position sticky will only stay at the top once it hits the top. If you want it always at the top you would have to move the actual element to the top and then use sticky – Pete Nov 22 '22 at 09:47
  • Does this help? https://stackoverflow.com/questions/17656623/position-absolute-scrolling – Adam Nov 22 '22 at 10:07

1 Answers1

0

Put the container you want to be on top at first and add position sticky and also top: 0 (important). You can also use position fixed but it will have some difficulties. Fixed position but relative to container
appendix: Do not write your styles inline. For clean code and readability.

.container {
  position: relative;
  height: 500px;
  max-height: 500px;
  overflow-y: auto;
}

.sticky-nav {
  position: sticky;
  top: 0;
  width: 100%;
  height: 112px;
  background-color: rgba(0, 0, 0, 0.2);
}

.sticky-nav div {
  width: fit-content;
  padding: 15px;
  color: white;
  border: 1px solid white;
  margin: 0 10px;
}
<div style="border: 1px solid black;">
  <div class="container">
    <div class="sticky-nav">
      <div>
        Button text
      </div>
    </div>

    <div style="width:100%; height: 500px;">
      <svg x="0" y="0" width="100%" height="800">
        <rect x="0" y="0" width="100%" height="800" fill="gold"></rect>
      </svg>
    </div>
  </div>
</div>
Amini
  • 1,620
  • 1
  • 8
  • 26
  • Thanks but it's not what I need. The gold container should start at the same point of the gay container. So the top-left point should be the same. At the moment the gold container starts ant the end of the gray one – whitecircle Nov 22 '22 at 11:23
  • I can use fixed but it's related to the browser which may not be the desired result because of I can have other elements before theese – whitecircle Nov 22 '22 at 11:27