Home > Mobile >  How do I position my element to be sticky (stay on screen when I scroll pass them)
How do I position my element to be sticky (stay on screen when I scroll pass them)

Time:02-19

I'm coding a basic eCommerce website using NextJS and I'm having a problem
I want to have a sticky tab in the middle of my page but for some reason position: 'sticky' doesn't work
This is my code

[other stuff here]

<div className={classes.stickyTab}>
   <Grid style={{ backgroundColor: '#FFFFFF' }}>
      <div className={classes.outerTab}>
        <div className={classes.innerTab}>
            <div>Tab number 1</div>
        </div>
      </div>
   </Grid>

   <Grid style={{ backgroundColor: '#FFFFFF' }}>
      <div className={classes.outerTab2}>
        <div className={classes.innerTab2}>
           <div>Tab number 2</div>
        </div>
      </div>
    </Grid>
</div>

[other stuff here]

And this is the styles.js

stickyTab: {
    position: 'sticky',
  },
outerTab: {
    display: 'flex',
    paddingTop: 16,
    paddingRight: 16,
    paddingBottom: 16,
    paddingLeft: 16,
  },
innerTab: {
    fontSize: '20px',
  },
outerTab2: {
    position: 'relative',
    marginTop: 10,
    marginBottom: 10,
  },
innerTab2: {
    position: 'relative',
    marginLeft: 10,
    marginRight: 10,
    marginBottom: 10,
  },

This is what it looks like visually enter image description here

Basically all I want is for my 2 white bars to be sticky so that they stay on the screen when I scroll pass them. All I did was wrap both of them inside a div then gave it position: 'sticky' but like I said it didn't work like I thought it would. Perhaps I'm missing something here?
Any helps would be much appreciated, thanks.

CodePudding user response:

Using position sticky property requires you to add the position also. Try adding top: 0; and width: 100% and height: 50px. You can have the width and height according to your needs.

stickyTab: { position: 'sticky', top:"0", width:'100%', height: '50px' }

  • Related