How to keep position of elements while child is scrolled

I need to keep buttons position in following snippet while horizontal scroll is proceed. But without fixed position usage as I want to get rid of crazy position calculations.

Thank You

<div style="position: relative; height: 100px; width: 400px; background-color: yellow; overflow: auto">
    <button style="position: absolute">
        must be visible all time
    </button>
    <button style="position: absolute; right: 0;">
        must be visible all time
    </button>
    <div style="height: 100px; width: 600px; background-color: red">
    <br>
      scroll this
    </div>
</div>

>Solution :

You can do a wrapper around the buttons and position them with sticky, set the position top and left to 0.

.container {
  position: relative;
  height: 100px;
  width: 400px;
  background-color: yellow;
  overflow: auto;
}

.container__actions {
  position: sticky;
  top: 0;
  left: 0;
  display: flex;
  justify-content: space-between;
  background-color: aqua;
}

.container__content {
  height: 100px;
  width: 600px;
  background-color: red;
}
<div class="container">
  <div class="container__actions">
    <button>
        must be visible all time
    </button>

    <button>
        must be visible all time
    </button>
  </div>

  <div class="container__content">
    <br> scroll this
  </div>
</div>

Leave a Reply