Add a Fixed Button to Scrollable Element

Published: Tuesday, July 21, 2020

Greetings, friends! There are times where you may want to add a button to a scrollable element, but the button should be fixed to that element. As the user scrolls, the button should remain visible and fixed to a certain position, relative to the scrollable element.

gif of scrollable content with a button fixed to the element

We'll start by adding some HTML:

Copied! ⭐️
<div class="box">
  <div class="content">
    <p>Line 1</p>
    <p>Line 2</p>
    <p>Line 3</p>
    <p>Line 4</p>
    <p>Line 5</p>
    <p>Line 6</p>
    <p>Line 7</p>
    <p>Line 8</p>
    <p>Line 9</p>
    <p>Line 10</p>
    <p>Line 11</p>
    <p>Line 12</p>
    <p>Line 13</p>
    <p>Line 14</p>
    <p>Line 15</p>

Then, we'll add the CSS. The most important thing to recognize is that the content is set to an overflow of auto, not the box. In this example, the user will be scrolling vertically, but you can allow horizontal scrolling if that fits your use case better. The button is set to a position of absolute to allow us to place it anywhere relative to the box.

Copied! ⭐️
.box {
  width: 500px;
  height: 300px;
  position: relative;
  background-color: cornflowerblue;

.content {
  overflow: auto;
  width: 100%;
  height: 100%;

button {
  position: absolute;
  bottom: 0.5rem;
  right: 0.5rem;

p {
  background-color: skyblue;

After adding both the HTML and CSS, make sure that there is room to scroll. You can always add extra lines in the HTML if you need more room.

That's all, folks! It doesn't take too much code to implement this technique. In fact, this approach to adding a fixed button to a scrollable element is actually being used throughout my entire website! If you look at the top-right corner of each code snippet on this page, you'll see the language type such as "html" or "css". If you are viewing this page on a small screen such as a phone, you may notice that the code snippet can be scrolled horizontally. As you scroll, the language type stays fixed and remains visible. This is just one application of the code you just learned today. I'm sure you can use this approach for other clever uses! Happy coding!