Try 'magnetic button'
View code

Specification

Catalogue
No. 95 of 110
Interaction
Layout Animation
Element
Text, Accordion
Preview
Live component
Imports
react 19.3.1, @number-flow/react 0.6.2, framer-motion 12.40.0
Added

Notes

Long text clamped to a few lines, with a soft fade over the last one. Read more opens it to its full height and Show less closes it. The control only appears when the text really runs past its lines.

Reviews, bios and product descriptions all need this, and most sites either cut the text with a hard edge or jump open. Here the height, the fade and the chevron follow one value, so they can never drift apart, and newly revealed lines rise through the soft edge instead of being uncovered by a line.

Opening takes 0.36s plus up to 0.1s for long text (distance / 1600); closing takes 0.2s plus up to 0.1s (distance / 2000); both cubic-bezier(.16, 1, .3, 1). The fade is a mask whose last 1.6 lines thin out by (1 - progress)^1.35. The clamp is lifted only after the height is pinned, so nothing jumps for a frame, and a hidden probe exactly that many lines tall decides whether the toggle is needed. The labels share one cell, so the button never changes width. The control is a 44px target. Instant under reduced motion.

The product and review are sample content; a client build uses the client's own.

Code

React and plain CSS
"use client";

import { useEffect, useId, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";
import { animate, motion, useMotionValue, useTransform, type AnimationPlaybackControls } from "framer-motion";
import type { LivePreviewProps } from "@/components/live/types";
import { EASE_ENTER } from "@/components/pieces/kit/physical-spring";
import { useSafeReducedMotion } from "@/components/pieces/kit/use-safe-reduced-motion";
import { layoutScale } from "@/components/pieces/motion-helpers";
import { Stars } from "@/components/pieces/shared";
import { PieceStage } from "@/components/pieces/stage/PieceStage";
import type { Tour } from "@/components/pieces/stage/tour";
import "./read-more.css";

/** Opening takes longer than closing, and both grow a little with the distance the text travels. */
const openFor = (px: number) => 0.36 + Math.min(px / 1600, 0.1);
const closeFor = (px: number) => 0.2 + Math.min(px / 2000, 0.1);

/** Height in layout pixels: the stage is scaled, so screen distances are divided back. */
const tall = (el: HTMLElement) => el.getBoundingClientRect().height / layoutScale(el);

function ReadMore({ lines = 3, children }: { lines?: number; children: ReactNode }) {
  const reduce = useSafeReducedMotion();
  const id = useId();
  const [open, setOpen] = useState(false);
  // The server renders the toggle (long text is the usual case); the first measurement removes it when the text fits.
  const [overflowing, setOverflowing] = useState(true);
  const [moving, setMoving] = useState(false);
  // The clamp only changes once a move ends, so the full height can be read before anything lifts.
  const [settled, setSettled] = useState(false);
  const box = useRef<HTMLDivElement>(null);
  const inner = useRef<HTMLDivElement>(null);
  const probe = useRef<HTMLSpanElement>(null);
  const clampH = useRef(0);
  const range = useRef({ from: 0, to: 0 });
  const run = useRef<AnimationPlaybackControls | null>(null);
  const last = useRef(open);

  // One value from 0 (clamped) to 1 (open) drives the height, the fade and the chevron, so they never drift apart.
  const progress = useMotionValue(0);
  const height = useMotionValue<number | "auto">("auto");
  const rotate = useTransform(progress, [0, 1], [0, 180]);
  const mask = useTransform(progress, (v) => {
    const fade = Math.pow(1 - Math.min(Math.max(v, 0), 1), 1.35);
    return fade <= 0.002 ? "none" : `linear-gradient(to bottom, #000 calc(100% - 1.6lh), rgb(0 0 0 / ${(1 - fade * 0.96).toFixed(3)}) 100%)`;
  });

  useEffect(
    () =>
      progress.on("change", (v) => {
        if (!run.current) return;
        const { from, to } = range.current;
        height.set(from + (to - from) * v);
      }),
    [progress, height],
  );

  useLayoutEffect(() => {
    const p = probe.current;
    const i = inner.current;
    if (!p || !i) return;
    const measure = () => {
      clampH.current = tall(p);
      setOverflowing(tall(i) > clampH.current + 1);
    };
    measure();
    const ro = new ResizeObserver(measure);
    ro.observe(p);
    ro.observe(i);
    return () => ro.disconnect();
  }, [lines]);

  useLayoutEffect(() => {
    if (last.current === open) return;
    last.current = open;
    const node = box.current;
    const i = inner.current;
    run.current?.stop();
    run.current = null;
    if (!node || !i || reduce) {
      progress.set(open ? 1 : 0);
      height.set("auto");
      setMoving(false);
      setSettled(open);
      return;
    }
    const full = tall(i);
    const clamp = Math.min(clampH.current, full);
    const current = tall(node);
    range.current = { from: clamp, to: full };
    const span = Math.max(full - clamp, 1);
    progress.jump(Math.min(Math.max((current - clamp) / span, 0), 1));
    // Pin today's height before the clamp lifts, so nothing jumps for a frame.
    height.set(current);
    setMoving(true);
    const target = open ? 1 : 0;
    const distance = Math.abs(target - progress.get()) * span;
    run.current = animate(progress, target, {
      duration: open ? openFor(distance) : closeFor(distance),
      ease: EASE_ENTER,
      onComplete: () => {
        run.current = null;
        height.set("auto");
        setMoving(false);
        setSettled(open);
      },
    });
  }, [open, reduce, progress, height]);

  useEffect(() => () => run.current?.stop(), []);

  const clamped = !settled && !moving && overflowing;
  const masked = overflowing && (!settled || moving);

  return (
    <div className="rm" style={{ "--rm-lines": lines } as CSSProperties}>
      <motion.div ref={box} id={id} className="rm-box" data-clamped={clamped || undefined} style={{ height, WebkitMaskImage: masked ? mask : "none", maskImage: masked ? mask : "none" }}>
        <span ref={probe} className="rm-probe" aria-hidden="true" />
        <div ref={inner}>{children}</div>
      </motion.div>
      {overflowing && (
        <button type="button" className="rm-toggle" aria-expanded={open} aria-controls={id} onClick={() => setOpen((o) => !o)}>
          <span className="rm-labels">
            <span data-on={!open || undefined} aria-hidden={open || undefined}>
              Read more
            </span>
            <span data-on={open || undefined} aria-hidden={!open || undefined}>
              Show less
            </span>
          </span>
          <motion.svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" style={{ rotate }}>
            <path d="m6 9 6 6 6-6" />
          </motion.svg>
        </button>
      )}
    </div>
  );
}

function ReadMoreDemo() {
  const uid = useId();
  return (
    <div className="rm-demo">
      <section className="rm-card" aria-labelledby={`${uid}-p`}>
        <h3 id={`${uid}-p`}>Oak hall bench</h3>
        <ReadMore>
          <p>
            Made to order from air-dried English oak, with through-tenons you can see on the ends and a seat planed by hand. Each bench takes about three weeks. It is finished in hard wax oil, which you refresh with a cloth once a year. Lengths from 90 to 180cm; the depth stays at 34cm for a narrow hall.
          </p>
        </ReadMore>
      </section>
      <section className="rm-card" aria-labelledby={`${uid}-r`}>
        <h3 id={`${uid}-r`} className="rm-who">
          <span>Priya, Leeds</span>
          <Stars />
        </h3>
        <ReadMore lines={2}>
          <p>Arrived wrapped in blankets rather than plastic, which says a lot. The oak has a lovely grain and the joints are tight. It is heavier than I expected, so plan for two people on the stairs. Three months on, it has not moved or marked at all.</p>
        </ReadMore>
      </section>
    </div>
  );
}

// What a hovered card shows: the description opening, then closing again.
const TOUR: Tour = [
  { click: ".rm-toggle", wait: 1400 },
  { click: ".rm-toggle", wait: 900 },
];

export default function ReadMoreEntry(props: LivePreviewProps) {
  return (
    <PieceStage {...props} label="Read more that glides open" tour={TOUR} sample>
      <ReadMoreDemo />
    </PieceStage>
  );
}

More like this

FAQ that opens smoothly

Layout AnimationCards and accordions

Form in named steps

Type, FeedbackForms and inputs

Menu that opens into link cards

Press, Layout AnimationNavigation

Cookie choice that folds away

FeedbackOverlays and toasts

Height that glides

Layout AnimationCards and accordions

Select with a gliding highlight

HoverForms and inputs