简体   繁体   中英

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

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在此处输入图像描述

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.

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' }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM