02Carousel That Snaps Back Like a Rubber Band at Its Edges
Pushing past the first or last card lets it stretch a little before snapping back into place the instant it's released, like a rubber band.
Best forA gallery that tells your fingertip there are no more pages, instantly
rawToVisualspringBackIfNeededonPointerMove

<main class="stage">
<section class="carousel is-demo" id="carousel" role="region" aria-roledescription="carousel" aria-label="Card carousel">
<div class="viewport" id="viewport" tabindex="0">
<div class="track" id="track">
<div class="card card--0"><span class="num">1</span></div>
<div class="card card--1"><span class="num">2</span></div>
<div class="card card--2"><span class="num">3</span></div>
<div class="card card--3"><span class="num">4</span></div>
<div class="card card--4"><span class="num">5</span></div>
</div>
</div>
<button type="button" class="navBtn navBtn--prev" id="prevBtn" aria-label="Previous card">
<svg viewBox="0 0 256 256" width="18" height="18" aria-hidden="true"><g fill="currentColor"><path d="M112 56v144l-72-72Z" opacity=".2"/><path d="M216 120h-96V56a8 8 0 0 0-13.66-5.66l-72 72a8 8 0 0 0 0 11.32l72 72A8 8 0 0 0 120 200v-64h96a8 8 0 0 0 0-16m-112 60.69L51.31 128L104 75.31Z"/></g></svg>
</button>
<button type="button" class="navBtn navBtn--next" id="nextBtn" aria-label="Next card">
<svg viewBox="0 0 256 256" width="18" height="18" aria-hidden="true"><g fill="currentColor"><path d="m216 128l-72 72V56Z" opacity=".2"/><path d="m221.66 122.34l-72-72A8 8 0 0 0 136 56v64H40a8 8 0 0 0 0 16h96v64a8 8 0 0 0 13.66 5.66l72-72a8 8 0 0 0 0-11.32M152 180.69V75.31L204.69 128Z"/></g></svg>
</button>
<div class="readout" id="readout" aria-live="polite"></div>
</section>
</main>@use "../../../../site/static/demo-tokens" as *;
// 변수 3개
$duration: $dur-base;
$easing: $ease-out;
$color: $subject-orange-deep;
// 계산 겹: index.html 의 rubber() 가 경계를 넘은 거리를 점근 곡선으로 눌러주고,
// springBackIfNeeded() 가 힘·감쇠를 매 프레임 더하는 스프링 물리로 경계까지 되돌린다.
@include stage($stage-ink);
.carousel {
position: relative;
width: 300px;
}
.viewport {
position: relative;
width: 300px;
height: 168px;
border-radius: $r-card;
overflow: hidden;
box-shadow: $shadow-raised;
background: $stage-ink;
outline: none;
}
.track {
display: flex;
height: 100%;
will-change: transform;
touch-action: none;
cursor: grab;
&.isDragging { cursor: grabbing; }
}
.card {
flex: 0 0 200px;
height: 100%;
margin-right: $sp-4;
border-radius: $r-card;
display: grid;
place-items: center;
&:last-child { margin-right: 0; }
.num {
font-weight: 700;
font-size: 56px;
line-height: 1;
}
}
.card--0 { background: linear-gradient(160deg, $subject-orange-deep, #905b47); .num { color: $subject-ink; } }
.card--1 { background: linear-gradient(160deg, $subject-pink, #d97fa0); .num { color: $subject-ink; } }
.card--2 { background: linear-gradient(160deg, $subject-mint, #63b299); .num { color: $subject-ink; } }
.card--3 { background: linear-gradient(160deg, $subject-lilac, #bdb3da); .num { color: $subject-ink; } }
.card--4 { background: linear-gradient(160deg, $subject-blue-deep, #475690); .num { color: $subject-cream; } }
.navBtn {
position: absolute;
top: 50%;
margin-top: -18px;
width: 36px;
height: 36px;
border-radius: $r-pill;
border: none;
display: grid;
place-items: center;
background: rgba($stage-ink, .6);
color: $subject-cream;
cursor: pointer;
&:focus-visible { outline: 2px solid $color; outline-offset: 2px; }
}
.navBtn--prev { left: -($sp-3); }
.navBtn--next { right: -($sp-3); }
.readout {
position: absolute;
left: $sp-3;
bottom: $sp-3;
padding: $sp-1 $sp-2;
border-radius: $r-pill;
background: rgba($stage-ink, .6);
color: rgba($subject-cream, .9);
font-size: 11px;
font-weight: 600;
line-height: 1;
font-variant-numeric: tabular-nums;
}
@media (max-width: 340px) {
.carousel { width: 220px; }
.viewport { width: 220px; height: 106px; }
.card { flex-basis: 148px; margin-right: $sp-2; .num { font-size: 36px; } }
.navBtn { width: 28px; height: 28px; margin-top: -14px; }
.readout { font-size: 9px; }
}
@media (prefers-reduced-motion: reduce) {
// 실사용 경로 적용 — 드래그·키보드·버튼은 index.html 이 그대로 고무줄·스프링 계산을 돌린다.
// scss 만: 포커스 아웃라인 전환만 꺼서 잔여 트랜지션을 없앤다.
.navBtn { transition: none; }
}html, body {
margin: 0;
overflow: hidden;
}
.stage {
box-sizing: border-box;
min-height: 100vh;
display: grid;
place-items: center;
margin: 0;
background: #17141a;
font-family: -apple-system, "Segoe UI", "Noto Sans KR", sans-serif;
padding: clamp(8px, 4vw, 24px);
}
.carousel {
position: relative;
width: 300px;
}
.viewport {
position: relative;
width: 300px;
height: 168px;
border-radius: 16px;
overflow: hidden;
box-shadow: 0 14px 24px rgba(23, 20, 26, 0.32);
background: #17141a;
outline: none;
}
.track {
display: flex;
height: 100%;
will-change: transform;
touch-action: none;
cursor: grab;
}
.track.isDragging {
cursor: grabbing;
}
.card {
flex: 0 0 200px;
height: 100%;
margin-right: 16px;
border-radius: 16px;
display: grid;
place-items: center;
}
.card:last-child {
margin-right: 0;
}
.card .num {
font-weight: 700;
font-size: 56px;
line-height: 1;
}
.card--0 {
background: linear-gradient(160deg, #c93000, #905b47);
}
.card--0 .num {
color: #17141a;
}
.card--1 {
background: linear-gradient(160deg, #ff9ebb, #d97fa0);
}
.card--1 .num {
color: #17141a;
}
.card--2 {
background: linear-gradient(160deg, #4cd4a6, #63b299);
}
.card--2 .num {
color: #17141a;
}
.card--3 {
background: linear-gradient(160deg, #b9a0ff, #bdb3da);
}
.card--3 .num {
color: #17141a;
}
.card--4 {
background: linear-gradient(160deg, #0a4fe8, #475690);
}
.card--4 .num {
color: #fff7e6;
}
.navBtn {
position: absolute;
top: 50%;
margin-top: -18px;
width: 36px;
height: 36px;
border-radius: 999px;
border: none;
display: grid;
place-items: center;
background: rgba(23, 20, 26, 0.6);
color: #fff7e6;
cursor: pointer;
}
.navBtn:focus-visible {
outline: 2px solid #c93000;
outline-offset: 2px;
}
.navBtn--prev {
left: -12px;
}
.navBtn--next {
right: -12px;
}
.readout {
position: absolute;
left: 12px;
bottom: 12px;
padding: 4px 8px;
border-radius: 999px;
background: rgba(23, 20, 26, 0.6);
color: rgba(255, 247, 230, 0.9);
font-size: 11px;
font-weight: 600;
line-height: 1;
font-variant-numeric: tabular-nums;
}
@media (max-width: 340px) {
.carousel {
width: 220px;
}
.viewport {
width: 220px;
height: 106px;
}
.card {
flex-basis: 148px;
margin-right: 8px;
}
.card .num {
font-size: 36px;
}
.navBtn {
width: 28px;
height: 28px;
margin-top: -14px;
}
.readout {
font-size: 9px;
}
}
@media (prefers-reduced-motion: reduce) {
.navBtn {
transition: none;
}
}(function () {
// 고무줄 저항 범위 — 경계를 넘는 거리가 아무리 커져도 시각적으로는 이 값(px)에 점근한다.
var RUBBER_BAND_RANGE = 64;
var SPRING_STIFFNESS = 0.22; // 목표까지 당기는 힘의 비율
var SPRING_DAMPING = 0.72; // 매 프레임 속도에 곱하는 감쇠(마찰)
var SPRING_STOP = 0.4; // 이 이하로 좁혀지면 스프링 정지
var STEP_MS = 16.6667;
var DEMO_PUSH_PX = 46;
var DEMO_HOLD_MS = 260;
var carousel = document.getElementById('carousel');
var viewport = document.getElementById('viewport');
var track = document.getElementById('track');
var readout = document.getElementById('readout');
var prevBtn = document.getElementById('prevBtn');
var nextBtn = document.getElementById('nextBtn');
var reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
var TOTAL = 5;
var LABEL_PREFIX = 'Card ';
var LABEL_SEP = ' / ';
var pos = 0, minX = 0, maxX = 0;
var dragging = false;
var springFrame = null;
var demoTimers = [];
function bounds() {
maxX = 0;
minX = Math.min(0, viewport.clientWidth - track.scrollWidth);
}
function clamp(v, lo, hi) { return Math.min(hi, Math.max(lo, v)); }
// 고무줄 감쇠 함수 — 넘어간 거리 o(항상 0 이상)를 RUBBER_BAND_RANGE 에 점근하는 곡선으로 눌러준다.
function rubber(o) {
return RUBBER_BAND_RANGE * o / (RUBBER_BAND_RANGE + o);
}
function rawToVisual(raw) {
if (raw > maxX) return maxX + rubber(raw - maxX);
if (raw < minX) return minX - rubber(minX - raw);
return raw;
}
function paint() {
track.style.transform = 'translate3d(' + pos.toFixed(1) + 'px,0,0)';
var step = track.scrollWidth / TOTAL;
var idx = clamp(Math.round(-clamp(pos, minX, maxX) / step), 0, TOTAL - 1);
readout.textContent = LABEL_PREFIX + (idx + 1) + LABEL_SEP + TOTAL;
}
function stopSpring() {
if (springFrame) { cancelAnimationFrame(springFrame); springFrame = null; }
}
// 스프링 복귀 — pos 가 경계를 넘은 채로 있을 때만 목표(가까운 경계)까지 힘·감쇠로 당겨 돌아온다.
function springBackIfNeeded() {
var target = pos > maxX ? maxX : (pos < minX ? minX : null);
if (target === null) return;
var velocity = 0;
function frame() {
var force = (target - pos) * SPRING_STIFFNESS;
velocity = (velocity + force) * SPRING_DAMPING;
pos += velocity;
paint();
if (Math.abs(velocity) > SPRING_STOP || Math.abs(target - pos) > SPRING_STOP) {
springFrame = requestAnimationFrame(frame);
} else {
pos = target;
paint();
springFrame = null;
}
}
springFrame = requestAnimationFrame(frame);
}
function human() {
if (carousel.classList.contains('is-demo')) {
carousel.classList.remove('is-demo');
demoTimers.forEach(function (t) { clearTimeout(t); });
demoTimers = [];
}
}
function onPointerDown(e) {
human();
stopSpring();
dragging = true;
track.classList.add('isDragging');
viewport.setPointerCapture(e.pointerId);
carousel._originPos = pos;
carousel._startX = e.clientX;
}
function onPointerMove(e) {
if (!dragging) return;
var dx = e.clientX - carousel._startX;
pos = rawToVisual(carousel._originPos + dx);
paint();
}
function onPointerUp(e) {
if (!dragging) return;
dragging = false;
track.classList.remove('isDragging');
try { viewport.releasePointerCapture(e.pointerId); } catch (err) {}
springBackIfNeeded();
}
function step(dir) {
human();
stopSpring();
var stepPx = track.scrollWidth / TOTAL;
pos = rawToVisual(clamp(pos + dir * -stepPx, minX - RUBBER_BAND_RANGE, maxX + RUBBER_BAND_RANGE));
paint();
springBackIfNeeded();
}
function onKeydown(e) {
if (e.key === 'ArrowLeft') { step(-1); e.preventDefault(); }
else if (e.key === 'ArrowRight') { step(1); e.preventDefault(); }
}
viewport.addEventListener('pointerdown', onPointerDown);
viewport.addEventListener('pointermove', onPointerMove);
viewport.addEventListener('pointerup', onPointerUp);
viewport.addEventListener('pointercancel', onPointerUp);
viewport.addEventListener('keydown', onKeydown);
prevBtn.addEventListener('click', function () { step(-1); });
nextBtn.addEventListener('click', function () { step(1); });
// reduce: 실사용 경로 적용 — 드래그·키보드·버튼은 위 리스너가 그대로 고무줄 계산을 돌린다.
// 아래 demoCycle() 은 시연 게이트만이고 reduce 에서는 돌지 않는다.
function pushAndRelease(target, onDone) {
var start = performance.now();
var from = pos;
function frame(now) {
if (!carousel.classList.contains('is-demo')) return;
var p = Math.min(1, (now - start) / 220);
pos = from + (target - from) * p;
paint();
if (p < 1) requestAnimationFrame(frame);
else {
springBackIfNeeded();
demoTimers.push(setTimeout(onDone, DEMO_HOLD_MS + 260));
}
}
requestAnimationFrame(frame);
}
function demoCycle(i) {
if (!carousel.classList.contains('is-demo')) return;
if (i % 2 === 0) {
pos = maxX; paint();
pushAndRelease(maxX + DEMO_PUSH_PX, function () { demoCycle(i + 1); });
} else {
pos = minX; paint();
pushAndRelease(minX - DEMO_PUSH_PX, function () { demoCycle(i + 1); });
}
}
function init() {
bounds();
paint();
if (!reduce) demoCycle(0);
}
window.addEventListener('resize', bounds);
init();
})();import { useEffect, useRef } from 'react';
import styles from './CarouselRubberBandEdge.module.scss';
// 상수 — vanilla demo 02 (run/384/demo/02-carousel-slide-rubber-band-edge/index.html) 과 동일
// 고무줄 저항 범위 — 경계를 넘는 거리가 아무리 커져도 시각적으로는 이 값(px)에 점근한다.
const RUBBER_BAND_RANGE = 64;
const SPRING_STIFFNESS = 0.22; // 목표까지 당기는 힘의 비율
const SPRING_DAMPING = 0.72; // 매 프레임 속도에 곱하는 감쇠(마찰)
const SPRING_STOP = 0.4; // 이 이하로 좁혀지면 스프링 정지
const DEMO_PUSH_PX = 46;
const DEMO_HOLD_MS = 260;
const TOTAL = 5;
const LABEL_PREFIX = '카드 ';
const LABEL_SEP = ' / ';
export default function CarouselRubberBandEdge() {
const carouselRef = useRef<HTMLElement>(null);
useEffect(() => {
const carousel = carouselRef.current;
if (!carousel) return undefined;
const viewport = carousel.querySelector<HTMLDivElement>('.' + styles.viewport);
const track = carousel.querySelector<HTMLDivElement>('.' + styles.track);
const readout = carousel.querySelector<HTMLDivElement>('.' + styles.readout);
const prevBtn = carousel.querySelector<HTMLButtonElement>('.' + styles['navBtn--prev']);
const nextBtn = carousel.querySelector<HTMLButtonElement>('.' + styles['navBtn--next']);
if (!viewport || !track || !readout || !prevBtn || !nextBtn) return undefined;
let pos = 0, minX = 0, maxX = 0;
let dragging = false;
let springFrame = 0;
let demoTimers: number[] = [];
let originPos = 0, startX = 0;
function bounds() {
maxX = 0;
minX = Math.min(0, viewport!.clientWidth - track!.scrollWidth);
}
function clamp(v: number, lo: number, hi: number) { return Math.min(hi, Math.max(lo, v)); }
// 고무줄 감쇠 함수 — 넘어간 거리 o(항상 0 이상)를 RUBBER_BAND_RANGE 에 점근하는 곡선으로 눌러준다.
function rubber(o: number) {
return RUBBER_BAND_RANGE * o / (RUBBER_BAND_RANGE + o);
}
function rawToVisual(raw: number) {
if (raw > maxX) return maxX + rubber(raw - maxX);
if (raw < minX) return minX - rubber(minX - raw);
return raw;
}
function paint() {
track!.style.transform = 'translate3d(' + pos.toFixed(1) + 'px,0,0)';
const step = track!.scrollWidth / TOTAL;
const idx = clamp(Math.round(-clamp(pos, minX, maxX) / step), 0, TOTAL - 1);
readout!.textContent = LABEL_PREFIX + (idx + 1) + LABEL_SEP + TOTAL;
}
function stopSpring() {
if (springFrame) { cancelAnimationFrame(springFrame); springFrame = 0; }
}
// 스프링 복귀 — pos 가 경계를 넘은 채로 있을 때만 목표(가까운 경계)까지 힘·감쇠로 당겨 돌아온다.
function springBackIfNeeded() {
const target = pos > maxX ? maxX : (pos < minX ? minX : null);
if (target === null) return;
const t: number = target;
let velocity = 0;
function frame() {
const force = (t - pos) * SPRING_STIFFNESS;
velocity = (velocity + force) * SPRING_DAMPING;
pos += velocity;
paint();
if (Math.abs(velocity) > SPRING_STOP || Math.abs(t - pos) > SPRING_STOP) {
springFrame = requestAnimationFrame(frame);
} else {
pos = t;
paint();
springFrame = 0;
}
}
springFrame = requestAnimationFrame(frame);
}
function human() {
if (carousel!.classList.contains(styles['is-demo'])) {
carousel!.classList.remove(styles['is-demo']);
demoTimers.forEach((t) => window.clearTimeout(t));
demoTimers = [];
}
}
function onPointerDown(e: PointerEvent) {
human();
stopSpring();
dragging = true;
track!.classList.add(styles.isDragging);
viewport!.setPointerCapture(e.pointerId);
originPos = pos;
startX = e.clientX;
}
function onPointerMove(e: PointerEvent) {
if (!dragging) return;
const dx = e.clientX - startX;
pos = rawToVisual(originPos + dx);
paint();
}
function onPointerUp(e: PointerEvent) {
if (!dragging) return;
dragging = false;
track!.classList.remove(styles.isDragging);
try { viewport!.releasePointerCapture(e.pointerId); } catch { /* 캡처가 이미 풀린 경우 */ }
springBackIfNeeded();
}
function step(dir: number) {
human();
stopSpring();
const stepPx = track!.scrollWidth / TOTAL;
pos = rawToVisual(clamp(pos + dir * -stepPx, minX - RUBBER_BAND_RANGE, maxX + RUBBER_BAND_RANGE));
paint();
springBackIfNeeded();
}
function onKeydown(e: KeyboardEvent) {
if (e.key === 'ArrowLeft') { step(-1); e.preventDefault(); }
else if (e.key === 'ArrowRight') { step(1); e.preventDefault(); }
}
function onPrev() { step(-1); }
function onNext() { step(1); }
function onResize() { bounds(); }
viewport.addEventListener('pointerdown', onPointerDown);
viewport.addEventListener('pointermove', onPointerMove);
viewport.addEventListener('pointerup', onPointerUp);
viewport.addEventListener('pointercancel', onPointerUp);
viewport.addEventListener('keydown', onKeydown);
prevBtn.addEventListener('click', onPrev);
nextBtn.addEventListener('click', onNext);
window.addEventListener('resize', onResize);
const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
// reduce: 실사용 경로 적용 — 드래그·키보드·버튼은 위 리스너가 그대로 고무줄 계산을 돌린다.
// 아래 demoCycle() 은 시연 게이트만이고 reduce 에서는 돌지 않는다.
function pushAndRelease(target: number, onDone: () => void) {
const start = performance.now();
const from = pos;
function frame(now: number) {
if (!carousel!.classList.contains(styles['is-demo'])) return;
const p = Math.min(1, (now - start) / 220);
pos = from + (target - from) * p;
paint();
if (p < 1) requestAnimationFrame(frame);
else {
springBackIfNeeded();
demoTimers.push(window.setTimeout(onDone, DEMO_HOLD_MS + 260));
}
}
requestAnimationFrame(frame);
}
function demoCycle(i: number) {
if (!carousel!.classList.contains(styles['is-demo'])) return;
if (i % 2 === 0) {
pos = maxX; paint();
pushAndRelease(maxX + DEMO_PUSH_PX, () => demoCycle(i + 1));
} else {
pos = minX; paint();
pushAndRelease(minX - DEMO_PUSH_PX, () => demoCycle(i + 1));
}
}
bounds();
paint();
if (!reduce) demoCycle(0);
return () => {
viewport.removeEventListener('pointerdown', onPointerDown);
viewport.removeEventListener('pointermove', onPointerMove);
viewport.removeEventListener('pointerup', onPointerUp);
viewport.removeEventListener('pointercancel', onPointerUp);
viewport.removeEventListener('keydown', onKeydown);
prevBtn.removeEventListener('click', onPrev);
nextBtn.removeEventListener('click', onNext);
window.removeEventListener('resize', onResize);
demoTimers.forEach((t) => window.clearTimeout(t));
stopSpring();
};
}, []);
return (
<main className={styles.stage}>
<section
className={styles.carousel + ' ' + styles['is-demo']}
ref={carouselRef}
role="region"
aria-roledescription="carousel"
aria-label="카드 캐러셀"
>
<div className={styles.viewport} tabIndex={0}>
<div className={styles.track}>
<div className={styles.card + ' ' + styles['card--0']}><span className={styles.num}>1</span></div>
<div className={styles.card + ' ' + styles['card--1']}><span className={styles.num}>2</span></div>
<div className={styles.card + ' ' + styles['card--2']}><span className={styles.num}>3</span></div>
<div className={styles.card + ' ' + styles['card--3']}><span className={styles.num}>4</span></div>
<div className={styles.card + ' ' + styles['card--4']}><span className={styles.num}>5</span></div>
</div>
</div>
<button type="button" className={styles.navBtn + ' ' + styles['navBtn--prev']} aria-label="이전 카드">
<svg viewBox="0 0 256 256" width={18} height={18} aria-hidden="true"><g fill="currentColor"><path d="M112 56v144l-72-72Z" opacity=".2" /><path d="M216 120h-96V56a8 8 0 0 0-13.66-5.66l-72 72a8 8 0 0 0 0 11.32l72 72A8 8 0 0 0 120 200v-64h96a8 8 0 0 0 0-16m-112 60.69L51.31 128L104 75.31Z" /></g></svg>
</button>
<button type="button" className={styles.navBtn + ' ' + styles['navBtn--next']} aria-label="다음 카드">
<svg viewBox="0 0 256 256" width={18} height={18} aria-hidden="true"><g fill="currentColor"><path d="m216 128l-72 72V56Z" opacity=".2" /><path d="m221.66 122.34l-72-72A8 8 0 0 0 136 56v64H40a8 8 0 0 0 0 16h96v64a8 8 0 0 0 13.66 5.66l72-72a8 8 0 0 0 0-11.32M152 180.69V75.31L204.69 128Z" /></g></svg>
</button>
<div className={styles.readout} aria-live="polite"></div>
</section>
</main>
);
}02 Carousel That Snaps Back Like a Rubber Band at Its Edges — Measured area 34.824% · moving frames 23/23Original by GODRICH · SCSS and React ship in the zip · Carousel Slider UI Design — 9 Transitions
The post this demo lives in
Carousel Slider UI Design — 9 TransitionsAmong nine carousel slider transitions, one glides on from inertia as a card advances, one snaps back like a rubber band See all demos in this post
If you like this effect - similar demos
Transitions01 Slide overshoot — a cart panel whose open position value passes its target before settling backCart Drawer UI Patterns: 9 Motion Techniques
Transitions05 Active-count badge pulse — a badge scaling by its change amount then settling back9 Filter UI Patterns (Panel Slide to Chip Remove)
Transitions04 Row-insert and position values changing together — when a new row is added, its position value settles into place while the rows below shift their position values tooCollapsible Table Row: 9 UI Patterns