实现Bootstrap卡片伪横向滚动效果(仿指定Codepen示例)
解决Bootstrap卡片在伪横向滚动效果中变形的问题
原示例的伪横向滚动依赖3D变换(perspective + rotateX)模拟横向滚动,但直接替换图片为Bootstrap卡片时,卡片的响应式布局类(如w-50)会和3D变换的坐标系冲突,导致卡片形态异常。以下是修复方案:
关键调整点
- 为每个Bootstrap卡片添加独立的包装容器,将3D变换作用在容器上,卡片本身保持Bootstrap的原有布局样式
- 确保卡片容器的尺寸足够容纳卡片,避免溢出变形
- 调整GSAP动画的目标为卡片容器,而非卡片元素
完整实现代码
HTML
<div class="scroll-container"> <div class="card-wrapper"> <div class="card w-50"> <div class="card-body"> <h5 class="card-title">Card title 1</h5> <p class="card-text">With supporting text below as a natural lead-in to additional content.</p> <a href="#" class="btn btn-primary">Button</a> </div> </div> </div> <div class="card-wrapper"> <div class="card w-50"> <div class="card-body"> <h5 class="card-title">Card title 2</h5> <p class="card-text">With supporting text below as a natural lead-in to additional content.</p> <a href="#" class="btn btn-primary">Button</a> </div> </div> </div> <!-- 可添加更多卡片包装器 --> </div>
CSS
.scroll-container { perspective: 400px; /* 保留原示例的透视效果 */ height: 100vh; overflow-y: auto; overflow-x: hidden; } .card-wrapper { transform-style: preserve-3d; margin: 2rem auto; /* 居中卡片容器 */ width: fit-content; /* 自适应卡片宽度 */ } /* 重置卡片受3D变换影响的样式 */ .card { transform: none !important; /* 禁止卡片自身被变换,由包装层承担3D变换 */ margin: 0; /* 移除卡片默认margin,避免布局偏移 */ }
JS(GSAP部分)
// 基于原示例动画逻辑,调整目标为.card-wrapper gsap.utils.toArray(".card-wrapper").forEach((cardWrap, index) => { gsap.fromTo(cardWrap, { rotationX: 45, yPercent: 100, opacity: 0 }, { scrollTrigger: { trigger: cardWrap, start: "top bottom", end: "bottom top", scrub: true }, rotationX: 0, yPercent: 0, opacity: 1, ease: "none" }); });
原理说明
- 包装层
.card-wrapper承接3D变换动画,卡片本身不受transform影响,完美保留Bootstrap的样式(如w-50的宽度比例) width: fit-content确保包装层只占用卡片所需宽度,避免不必要的留白transform: none !important强制卡片不继承包装层的3D变换,保证卡片布局正常
内容的提问来源于stack exchange,提问作者execOQ
相关产品推荐
相关产品推荐

