Home > Software design >  How to keep position of elements while child is scrolled
How to keep position of elements while child is scrolled

Time:07-27

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>

CodePudding user response:

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 >
  <div >
    <button>
        must be visible all time
    </button>

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

  <div >
    <br> scroll this
  </div>
</div>

CodePudding user response:

you can use sticky

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

  • Related