Springs in plain CSS

By the end you will know how stiffness, damping and mass turn into a list of points, how CSS linear() replays them, and the one thing a CSS spring still cannot do.

ExperimentMotion
01

A spring is a list of points

CSS has no spring() function, but it can replay a spring. You simulate the spring once from three numbers (stiffness, damping and mass), record its position at a series of moments, and pass that list to the linear() easing function. The browser joins the points with straight lines and plays them over a fixed duration. The result is a plain CSS transition that moves like a spring, with no JavaScript running during the motion.

Same transition, two easings Interactive
ease-out
spring as linear()
Press Play both.

Press Play both a few times. The left dot uses ease-out. It slows down and stops. The right dot runs past the end, swings back and settles. Both are ordinary transitions on transform. Their easing differs, and so does their duration, because the spring needs its own settle time.

This article builds that value from the physics up. It then checks how closely your browser replays it, and shows the one place where a CSS spring still loses to a few lines of script. If cubic-bezier curves are new to you, start with Easing curves you can feel.

02

Three numbers, one force

A spring follows one rule. The further the object is from its target, the harder it is pulled back. The strength of that pull is the stiffness, k. Damping, c, is friction that grows with speed, so every swing loses some energy. Mass, m, is how much the object resists a change in speed. Together they give the acceleration: (−k × (x − target) − c × v) / m, where x is position and v is velocity.

Spring lab Interactive
Move a slider to retune the spring.linear(…)

The dashed line is the simulated spring. The orange dots are the points that become your linear() value, and the solid line joins them the way the browser will. Lower the damping and the curve rings for longer, and the duration grows with it. Raise the mass and the motion gets slower and swings wider. Doubling the mass gives the same motion as halving both stiffness and damping, because the equation divides both by m. A single spring really has only two free settings.

The summary starts with the damping ratio, c / (2√(k·m)). Below 1, the spring overshoots. At exactly 1, it reaches the target as fast as it can without passing it. Above 1, it creeps in slowly. That one number predicts the character of the motion better than any single slider.

One level deeper. The lab does not solve a formula. It steps time forward 0.25 ms at a time: compute the force, update the velocity, then move the position using the new velocity. That order is called semi-implicit Euler. The naive order, which moves the position with the old velocity, adds a little energy on every step, so it makes a spring ring more than it should. The loop stops once the position is within 0.1% of the target and nearly still. That moment becomes the duration.

</> Simulate once, keep one position per millisecond.Show code
function sampleSpring(k, c, m) {
  const xs = [0];                     // one position per millisecond
  let x = 0, v = 0;
  const h = 0.00025;                  // 0.25 ms physics step
  while (xs.length <= 4000) {         // give up after 4 s
    for (let i = 0; i < 4; i++) {
      v += (-k * (x - 1) - c * v) / m * h;  // velocity first
      x += v * h;                           // then position
    }
    xs.push(x);
    if (Math.abs(x - 1) < 0.001 && Math.abs(v) < 0.02) break;
  }
  xs[xs.length - 1] = 1;              // land exactly on the target
  return xs;                          // duration in ms = xs.length - 1
}
03

linear() connects the dots

linear() takes a list of output values. Without percentages, the values are spread evenly across the duration, so linear(0, 0.6, 1) reaches 0.6 halfway through. A percentage pins a value to a moment in time. Values above 1 are allowed, and that is how the dot passes its end and comes back. Between two neighboring points the browser draws a straight line, so the motion is only as smooth as the list is dense.

</> The whole syntax in three lines.Show code
/* No percentages: values are spread evenly over the duration */
transition-timing-function: linear(0, 0.6, 1);

/* A percentage pins a value to a moment; 1.2 overshoots by 20% */
transition-timing-function: linear(0, 1.2 30%, 0.95 55%, 1);

/* Two percentages hold one value: a flat step from 40% to 60% */
transition-timing-function: linear(0, 0.5 40% 60%, 1);

A cubic-bezier() can overshoot too, but a single cubic curve has at most two turning points. It can go past the end once and come back. A spring that rings needs more turns than that.

What your browser actually plays Interactive
Checking linear() support…Press Play and record.

Press Play and record. The dot runs the lab's current spring through element.animate(). On every frame, the script reads the dot's computed transform back from the browser. Each orange dot is one of those readings, placed at the animation's currentTime. The first number in the result compares the readings with the straight lines through your points, which tests whether your engine replays the list faithfully. The second compares them with the simulated spring, so it also includes the sampling error that section 4 is about. The first readout shows how your browser stores a short linear() value, including whether it writes back the percentages it filled in.

One level deeper. The browser never learns that this is a spring. On each frame it turns elapsed time into input progress from 0 to 1, finds the two points on either side, interpolates between their outputs, and passes that number to the normal interpolation of the property. For transform, an output above 1 simply carries the motion past the end value. Properties with a limited range are clamped after interpolation, so a spring on opacity that ends at 1 just flattens at 1.

linear() works wherever an easing does: transition-timing-function, animation-timing-function and the easing option of element.animate(). It is supported in Chrome and Edge 113, Firefox 112 and Safari 17.2 or later. The readout above checks your browser instead of relying on that list.

04

How many points is enough

Every point adds characters to your stylesheet. With too few points, two things go wrong. The peak can get shaved off, because a sample rarely lands exactly on the true peak. And the motion becomes faceted: the speed stays constant along each segment and jumps where the segments meet. Drag the slider down and watch both happen.

Spend fewer points Interactive
Curve-aware points
Move the slider.Counting points…

Now turn on Curve-aware points. Evenly spaced points spend part of the budget on the long, nearly flat tail, where the spring has almost stopped. The curve-aware method keeps the first and last samples, then keeps adding the sample that the current straight lines miss by the most. The points gather in the bends. The trade-off is text: each curve-aware point between the two ends needs its own percentage.

The second readout answers the practical question for the spring you tuned in section 2: how many points each method needs to stay within 1 px on a 300 px move, and how many characters each of those two lists costs. Compare both pairs of numbers before you choose, because the point count alone does not tell you how long the CSS will be. Then lower the damping in the lab and measure again.

Measure the error in pixels. The same curve can be invisible on one element and wrong on another. A gap of 1% of the travel is 0.2 px on a 20 px nudge and 6 px on a 600 px drawer. Choose the point budget for the longest distance the animation will cover.

</> Keep adding the sample the lines miss by the most.Show code
function pickPoints(xs, budget) {
  const keep = [0, xs.length - 1];
  while (keep.length < budget) {
    let worst = 0, at = 0;
    for (let s = 0; s < keep.length - 1; s++) {
      const a = keep[s], b = keep[s + 1];
      for (let j = a + 1; j < b; j++) {
        const line = xs[a] + (xs[b] - xs[a]) * (j - a) / (b - a);
        const miss = Math.abs(line - xs[j]);
        if (miss > worst) { worst = miss; at = j; }
      }
    }
    if (!worst) break;
    keep.push(at);
    keep.sort((p, q) => p - q);
  }
  const pct = i => (i / (xs.length - 1) * 100).toFixed(2);
  return `linear(${keep.map(i => `${xs[i].toFixed(4)} ${pct(i)}%`).join(', ')})`;
}
05

Where CSS springs break

Two limits come from the same fact: linear() turns time into progress, and does nothing else. First, the duration is fixed. The spring's settle time is built into the points, and transition-duration has to match it. If you stretch the duration, you no longer play the spring you simulated. Second, an easing function has no idea how fast the element is already moving when it starts. That matters as soon as a motion is interrupted.

Interrupt both mid-flight Interactive
CSS transition with linear()
JavaScript spring
Press Go, then press it again while the dots move.

Press Go, then press it again while the dots are still moving. For a repeatable test, press Go, reverse at 150 ms. The reversal happens on the first frame at or after that time. The left lane is a CSS transition using the lab's linear(). The right lane, in teal, is the same spring stepped in JavaScript on every frame. Until the reversal, their lines on the graph should run close together. At the dashed marker they part.

With the default spring, the CSS line turns a sharp corner. The dot starts again from the beginning of the curve, and a spring released from rest begins almost flat, so it abruptly loses the speed it had. The JavaScript line bends instead. The dot keeps its speed, slows down and swings back. The readout measures both speeds on either side of the reversal and how long each dot takes to settle afterwards.

One level deeper. When a property that is already transitioning gets a new value, the CSS Transitions spec starts a new transition from the current animated value, so the position does not jump. If the new target is the previous start value, the browser also shortens the duration, using what the spec calls the reversing shortening factor. That can make the CSS settle time in the readout shorter than a full run. The speed is never carried over. Every new transition starts at the beginning of its easing curve.

You can patch this from script. Read the velocity at the interruption, simulate a new spring that starts with that velocity, and start a fresh transition with the new linear(). But at that point you are already running the physics in JavaScript, and a direct spring is simpler. Sliders that fight back uses one to throw a thumb back at the speed of your hand.

</> A JavaScript spring keeps its velocity when the target changes.Show code
let x = 0, v = 0, target = 0, last = 0, running = false;

function frame(now) {
  const dt = Math.min(0.032, (now - (last || now)) / 1000);
  last = now;
  for (let i = 0; i < 8; i++) {           // 8 small steps per frame
    v += (-k * (x - target) - c * v) / m * (dt / 8);
    x += v * (dt / 8);
  }
  el.style.transform = `translateX(${x * distance}px)`;
  running = Math.abs(x - target) > 0.001 || Math.abs(v) > 0.01;
  if (running) requestAnimationFrame(frame); else last = 0;
}

// Interrupting is one assignment: x and v carry straight on.
function retarget(to) {
  target = to;
  if (!running) { running = true; requestAnimationFrame(frame); }
}
06

A calmer curve on request

Some people turn on their system's reduce-motion setting because movement on screen can make them dizzy or sick, including people with vestibular disorders. Overshoot and wobble add movement that carries no information. Removing every cue is not the only answer, because the change of state may still need to be seen. In this example, we keep a short move and drop the bounce. For large or page-wide motion, remove the movement.

Full spring or calm curve Interactive
Reduced motion
Reading your system setting…

The moving demos on this page wait for your input and stop on their own. Nothing loops or plays on scroll.

The switch starts at your real system setting and lets you preview the other one. The fallback is the same spring with its damping raised to a damping ratio of exactly 1, so it arrives without passing the target. It is then compressed into 200 ms. The graph puts both curves on one time axis: the dashed full spring and the solid curve you have selected.

</> One media query swaps the curve (values shortened).Show code
:root {
  --spring: linear(0, 0.0123 2.5%, …, 1);   /* full spring from the lab */
  --spring-time: 1080ms;
}
@media (prefers-reduced-motion: reduce) {
  :root {
    --spring: linear(0, 0.0431 4%, …, 1);   /* critically damped */
    --spring-time: 200ms;
  }
}
.sheet {
  transition: transform var(--spring-time) ease-out;
  transition-timing-function: var(--spring);
}

The spring variable sits in its own transition-timing-function line on purpose. Section 7 explains what that protects. If you need the setting in script, matchMedia('(prefers-reduced-motion: reduce)') gives a live answer, and its change event fires when the user flips the setting. The demo above listens to it.

07

Take your spring with you

The block below is generated from the spring you tuned in section 2. Change the sliders there and it updates here. It already includes the reduced-motion fallback from section 6.

Your spring as CSS Interactive
Tune the spring in section 2.

Notice the two declarations in the first rule. transition sets ease-out, and the next line replaces it with a literal linear(). A browser that cannot parse linear() drops that second declaration while reading the stylesheet, so ease-out stays.

The custom-property version in section 6 falls back differently. The browser cannot check what var(--spring) contains while reading the stylesheet. It keeps the declaration, which overrides ease-out. If the substituted linear() is unsupported, the declaration fails later, when the value is computed. Only transition-timing-function resets, to its initial value, ease. It does not return to the earlier ease-out. The property and duration from the shorthand remain, so the element still animates.

Do not move var(--spring) into the transition shorthand. There, an unsupported linear() makes the whole shorthand fail, and every longhand resets to its initial value. That includes a transition-duration of 0s, so the element jumps with no animation at all. Current versions of all major browsers support linear(), so these fallbacks only matter for older ones.

If the spring never plays on an element you have just inserted, check the start state before you blame the curve. Transitions that skip the start explains the fix.

Use a linear() spring for motion that usually runs to the end once it starts: a menu or sheet opening, a toast arriving, a toggle snapping into place (Elastic toggles covers springy switches). It needs no per-frame script of yours and works with transitions, keyframe animations and element.animate(). Use a JavaScript spring when the motion follows a hand or often changes direction mid-flight: drag to dismiss, sliders, carousels, anything released with a fling. There, the starting speed is the whole point, and a ready-made linear() list cannot take it as an input. Skip the spring for large page-wide moves, for clamped properties like opacity, or when the reader asks for reduced motion. In the last case, use the calm curve for small moves and remove large ones.

Quick answers

Can you make a spring animation in pure CSS?
Yes, although CSS has no spring() function. You simulate the spring in advance from stiffness, damping and mass, record its position over time, and pass those points to the linear() easing function. Set the duration to match the spring’s settle time. The browser then replays the movement with no JavaScript running during the motion.

Can cubic-bezier() create a spring effect in CSS?
Only a simple one. A cubic-bezier() easing can overshoot, but a single cubic curve has at most two turning points. It can pass the end once and come back, but a spring that keeps ringing needs more turns. The linear() function can follow them because it accepts many points, including output values above 1.

Which browsers support the CSS linear() easing function?
Chrome and Edge 113, Firefox 112, Safari 17.2 and later versions support linear(). For older browsers, set a transition with ease-out first, then override its timing function with a literal linear() value, which they drop so ease-out stays. If that transition-timing-function override uses var() instead, an unsupported linear() resets only the timing function to its initial value, ease, not to your earlier ease-out.

How many points does a linear() spring need?
It depends on the spring and how far the element moves. Too few points can clip the peak and make the motion faceted. Measure error in pixels: a 1% gap is 0.2 px over 20 px, but 6 px over 600 px. Choose for the longest distance, and compare evenly spaced points with points concentrated in the bends.

Why does my CSS spring jerk when interrupted or reversed?
A CSS transition continues from the current position when its target changes, but it does not carry over speed. The new transition starts at the beginning of the linear() curve. A spring released from rest starts almost flat, so the element abruptly slows. For drags, flings or frequent reversals, use a JavaScript spring that keeps velocity.

New deep dives, in your inbox.