Ondřej Michejda
Ondřej Michejda

Reputation: 158

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>

Upvotes: 1

Views: 31

Answers (2)

Ahmed hassanin
Ahmed hassanin

Reputation: 1

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>

Upvotes: 0

Dejan.S
Dejan.S

Reputation: 19128

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>

Upvotes: 2

Related Questions