AdamHinckley
AdamHinckley

Reputation: 235

How to get a component to be fixed at the bottom until the user scrolls to the footer with CSS in React

I am using React and CSS in JS with Emotion. When on mobile, I need a button to be fixed at the bottom of the viewport until the user scrolls to the footer. At that point, it needs to be fixed at the top of the footer.

The button is a reusable component that can be dropped in where it's needed and be shown/hidden with media queries.

I have tried

position: fixed;
bottom: 0;

☝️ That works great until the footer is in view. I need it to stick to the top of the footer.

I have also tried

position: sticky;
top: (some amount of px);

For some reason, position sticky has no effect in this situation. I assume it doesn't work in child components (it does work on the header).

If there is a way to get position: sticky to work in a child component, please share that with me. I am open to any other approaches as well. Additionally, we are using Material UI, if there is a lesser known feature that will work with MUI that is an option too.

Upvotes: 1

Views: 4564

Answers (2)

Jonathan Irwin
Jonathan Irwin

Reputation: 5787

You could use react-use-scroll to get the user scroll position and change your styles in emotion after some scroll value

Upvotes: 1

Matan Sanbira
Matan Sanbira

Reputation: 1513

it's a bit fussy but if the sticky elements parents are siblings it can work.

a small POC:

.content {
  margin-top: -50px;
  background: grey;
  height: 1000px;
}

.btn {
  position: sticky;
  width: 50px;
  height: 50px;
  background: red;
  top: calc(100vh - 55px);
  z-index: 10;
}

.footer {
  position: sticky;
  width: 100%;
  height: 40px;
  background: blue;
  top: 0;
}
<div class="container">

  <div>
    <div class="btn"></div>
    <div class="content"></div>
  </div>


  <div>
    <div class="footer"></div>
  </div>

</div>

Upvotes: 1

Related Questions