滚动时Sticky卡片无法固定的CSS问题求助
解决Sticky卡片无法固定的问题
你的代码里右侧Sticky卡片不生效的核心原因是父flex容器设置了固定高度height={'150rem'},flex布局特性加上固定高度,把sticky元素的定位参考范围限制在了父容器内部,无法相对于视口实现固定效果。
修复步骤:
- 移除父Box的固定高度
height={'150rem'},让容器高度由左侧内容自然撑开 - 保留
alignSelf={'flex-start'}和top={0},这两个属性是sticky生效的必要配置 - 确保父容器没有设置
overflow: hidden(默认值visible符合要求)
修正后的代码:
<Box display={'flex'} width={'100%'}> <Box width={'100%'}> {features.map((feature) => ( <div key={feature.id}> <Typography variant='h2' py={10} color={'grey'}> {feature.title} </Typography> </div> ))} </Box> <Box position={'sticky'} width={'100%'} sx={{ backgroundColor: 'grey' }} top={0} height={'50rem'} alignSelf={'flex-start'} > sticky card placeholder </Box> </Box>
原理补充:
position: sticky的生效必须满足两个关键条件:
- 必须设置
top/right/bottom/left中的至少一个定位偏移值 - 元素的父容器不能限制其滚动范围(比如固定高度、设置
overflow: hidden/auto/scroll),否则sticky只会在父容器内部生效
内容的提问来源于stack exchange,提问作者Fatih Can
相关产品推荐
相关产品推荐

