Skip to content

176 web animation techniques, each a live demo with plain settings and a ready-made prompt for your AI assistant. No dependencies, no build step.

35.4 KB
Raw Blame
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>3D Flip Card — Animation Handbook</title>
  <meta name="description" content="A card turns over in 3D to show its back. Best for profile and product cards.">
  <link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/flip-card-3d/">
  <link rel="icon" type="image/png" sizes="96x96" href="../../../favicon.png">
  <link rel="icon" type="image/svg+xml" href="../../../favicon.svg">
  <link rel="apple-touch-icon" href="../../../apple-touch-icon.png">
  <meta property="og:type" content="article">
  <meta property="og:site_name" content="Animation Handbook">
  <meta property="og:title" content="3D Flip Card — Animation Handbook">
  <meta property="og:description" content="A card turns over in 3D to show its back. Best for profile and product cards.">
  <meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/flip-card-3d/">
  <meta property="og:image" content="https://matinmonshizadeh.github.io/animation-handbook/og-image.png">
  <meta name="twitter:card" content="summary_large_image">
  <meta name="twitter:title" content="3D Flip Card — Animation Handbook">
  <meta name="twitter:description" content="A card turns over in 3D to show its back. Best for profile and product cards.">
  <meta name="twitter:image" content="https://matinmonshizadeh.github.io/animation-handbook/og-image.png">
  <script type="application/ld+json">{"@context": "https://schema.org", "@type": "TechArticle", "headline": "3D Flip Card", "name": "3D Flip Card", "description": "A card turns over in 3D to show its back. Best for profile and product cards.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/flip-card-3d/", "inLanguage": "en", "articleSection": "3D & Advanced", "isPartOf": {"@type": "WebSite", "name": "Animation Handbook", "url": "https://matinmonshizadeh.github.io/animation-handbook/"}, "author": {"@type": "Person", "name": "matinmonshizadeh"}, "keywords": "web animation, CSS animation, 3D & Advanced, 3D Flip Card"}</script>
  <style>
    :root{--ui-accent:#3fd6c4;--perspective:1200px;--flip-dur:650ms}
    *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
    .stage{position:relative;background:radial-gradient(120% 120% at 50% 0%,#141018,#08070a);display:flex;align-items:center;justify-content:center;padding:clamp(20px,4vw,48px);perspective:var(--perspective)}
    /* A window under 657px tall gives the stage 260 to 326px, so the stage gives up padding as the window shrinks and the card
       keeps the 156×218 it has on a 1366×657 laptop, the smallest size that holds its text on one line */
    @media(min-width:601px) and (max-height:656px){.stage{padding:clamp(14px,calc(50vh - 281px),48px);padding:clamp(14px,calc(50svh - 281px),48px)}}
    /* Tilt wrapper carries the idle cursor-driven 3D tilt; it fills the stage so the card sits on the middle of the perspective.
       It lies in the same plane as the card, so a tilted wrapper would win some hit tests and swallow clicks meant for the card:
       only the card takes the pointer. */
    .tilt{width:100%;height:100%;display:flex;align-items:center;justify-content:center;transform-style:preserve-3d;transition:transform 300ms ease;pointer-events:none}
    .tilt.tracking{transition:none}
    /* Card — the flipping element, sized from the stage's height (5:7, at most 340px tall) */
    .card{flex:none;height:min(95%,340px);width:auto;aspect-ratio:5/7;position:relative;transform-style:preserve-3d;cursor:pointer;pointer-events:auto;
      transition:transform var(--flip-dur) cubic-bezier(.6,.02,.2,1);will-change:transform}
    .card.flipped{transform:rotateY(180deg)}
    .card.axis-x.flipped{transform:rotateX(180deg)}
    .hb-page .stage .card:focus-visible{outline:2px solid var(--ui-accent);outline-offset:6px;border-radius:16px}
    .face{
      position:absolute;inset:0;border-radius:16px;overflow:hidden;
      backface-visibility:hidden;-webkit-backface-visibility:hidden;
      transform:translateZ(0);
      border:1px solid rgba(255,255,255,.12);
      box-shadow:0 24px 60px rgba(0,0,0,.55);
      display:flex;flex-direction:column;padding:clamp(16px,4%,24px)
    }
    /* Front — profile face */
    .front{background:linear-gradient(150deg,#2a1a4a,#1a1030)}
    .card.axis-x .back{transform:rotateX(180deg)}
    .card:not(.axis-x) .back{transform:rotateY(180deg)}
    .avatar{width:56px;height:56px;border-radius:50%;background:linear-gradient(135deg,#b98cff,#6d4ea8);display:flex;align-items:center;justify-content:center;font-weight:800;font-size:22px;color:#0b0b0d}
    .front .name{font-weight:700;font-size:clamp(16px,2.4vw,22px);margin-top:auto;color:#fff;line-height:1.15}
    .front .role{font-size:11px;color:#b98cff;letter-spacing:1px;margin-top:6px;text-transform:uppercase}
    .front .hint{font-size:11px;color:rgba(255,255,255,.6);margin-top:14px;letter-spacing:.5px}
    /* Back — details face */
    .back{background:linear-gradient(150deg,#120c1e,#0d0a16)}
    .back .over{font-size:11px;font-weight:600;letter-spacing:2px;text-transform:uppercase;color:#b98cff}
    .back .row{display:flex;justify-content:space-between;font-size:11px;color:rgba(255,255,255,.7);padding:8px 0;border-bottom:1px solid rgba(255,255,255,.07)}
    .back .row span:last-child{color:#fff}
    .back .rows{margin-top:auto}
    .back .hint{font-size:11px;color:rgba(255,255,255,.6);margin-top:14px;letter-spacing:.5px}
    /* Tilt only on true hover-capable pointers */
    @media(hover:hover){.tilt{will-change:transform}}
    @media(hover:none){.tilt{transform:none!important}}
    /* Reduced motion — a quick fade between the faces, no tilt, no rotation */
    @media(prefers-reduced-motion:reduce){
      .card{transition:none!important;transform:none!important}
      .tilt{transition:none!important;transform:none!important}
      .face{backface-visibility:visible;-webkit-backface-visibility:visible;transition:opacity 120ms linear}
      .card:not(.axis-x) .back,.card.axis-x .back{transform:none}
      .back{opacity:0}
      .card.flipped .front{opacity:0}
      .card.flipped .back{opacity:1}
    }
    /* See inside and Compare. The tilt sits in a box that takes no part in the layout until a mode needs it. */
    .half{display:contents}
    .half.copy,.cap,.lead,.dash,.axis,.arrow{display:none}
    .cap{position:absolute;z-index:2;padding:2px 7px;border-radius:6px;background:rgba(11,11,13,.92);color:#f4f4f2;font:600 12px/15px var(--hb-font);white-space:nowrap;pointer-events:none}
    .lead{position:absolute;inset:0;width:100%;height:100%;pointer-events:none}
    .lead path{fill:none;stroke:rgba(244,244,242,.75);stroke-width:1.5}
    .lead circle{fill:#f4f4f2;stroke:#0b0b0d;stroke-width:1}
    .dash{position:absolute;inset:0;border:2px dashed rgba(244,244,242,.85);border-radius:16px;backface-visibility:visible;-webkit-backface-visibility:visible}
    .axis{position:absolute;left:50%;top:50%;translate:-50% -50%;border-radius:2px;background:#ffcf5c}
    .arrow{position:absolute;left:50%;top:50%;width:40px;height:24px;fill:none;stroke:#ffcf5c;stroke-width:3;stroke-linecap:round;stroke-linejoin:round}
    /* See inside: the card pulled apart, seen from three quarters (the script sets the view, the gap and the gold line's size) */
    .stage[data-hb-mode="inside"] .half.real{display:flex;flex:none;width:100%;height:100%;transform-style:preserve-3d;pointer-events:none}
    .stage[data-hb-mode="inside"] .tilt{position:relative}
    .stage[data-hb-mode="inside"] .dash,.stage[data-hb-mode="inside"] .axis,.stage[data-hb-mode="inside"] .arrow,.stage[data-hb-mode="inside"] .in-cap,.stage[data-hb-mode="inside"] .lead{display:block}
    .stage[data-hb-mode="inside"] .face{box-shadow:none}
    .stage[data-hb-mode="inside"] .front,.stage[data-hb-mode="inside"] .d-f{transform:translateZ(var(--gap))}
    .stage[data-hb-mode="inside"] .card:not(.axis-x) .back,.stage[data-hb-mode="inside"] .card:not(.axis-x) .d-b{transform:rotateY(180deg) translateZ(var(--gap))}
    .stage[data-hb-mode="inside"] .card.axis-x .back,.stage[data-hb-mode="inside"] .card.axis-x .d-b{transform:rotateX(180deg) translateZ(var(--gap))}
    .stage[data-hb-mode="inside"].xturn .arrow{rotate:-90deg}
    /* Compare: two halves, each with its own perspective; "Back shows through" is the copy, which leaves the back face visible from
       behind, so the back is painted over the front (mirrored). Each card keeps the 156 x 218 layout that holds its text on one line
       and is scaled to its half. */
    .stage[data-hb-mode="compare"]{perspective:none;padding:0 8px;--cmp-top:34px}
    .stage[data-hb-mode="compare"] .half{display:flex;flex:1 1 0;min-width:0;align-self:stretch;padding-top:var(--cmp-top);perspective:var(--perspective);perspective-origin:50% calc(50% + var(--cmp-top)/2);pointer-events:none}
    .stage[data-hb-mode="compare"] .half.real{box-shadow:inset 1px 0 0 rgba(255,255,255,.12)}
    .stage[data-hb-mode="compare"] .card{width:156px;height:218px;scale:var(--cs,1)}
    .stage[data-hb-mode="compare"] .copy .face{backface-visibility:visible;-webkit-backface-visibility:visible}
    .stage[data-hb-mode="compare"] .cmp-name{display:block;top:8px;left:calc(8px + (100% - 16px)/4);translate:-50% 0}
    .stage[data-hb-mode="compare"] .cmp-name.two{left:calc(8px + (100% - 16px)*.75)}
    @media(prefers-reduced-motion:reduce){
      /* See inside shows the turn as a still, a third of the way: the pose outranks the rules above, which pose nothing */
      .stage[data-hb-mode="inside"] .card{--r:0 1 0;--a:60deg;rotate:var(--r) var(--a)}
      .stage[data-hb-mode="inside"] .card.flipped{--a:120deg}
      .stage[data-hb-mode="inside"] .card.axis-x{--r:1 0 0}
      .stage[data-hb-mode="inside"] .card .face{backface-visibility:hidden;-webkit-backface-visibility:hidden;opacity:1}
      /* Compare: the copy shows its back over its front, mirrored, until it is turned over */
      .stage[data-hb-mode="compare"] .copy .face{opacity:1}
      .stage[data-hb-mode="compare"] .copy .card:not(.axis-x):not(.flipped) .back{transform:rotateY(180deg)}
      .stage[data-hb-mode="compare"] .copy .card.axis-x:not(.flipped) .back{transform:rotateX(180deg)}
    }
  </style>
  <link rel="stylesheet" href="../../../assets/css/demo-page.css?v=11">
  <script src="../../../assets/js/demo-page.js?v=11" defer></script>
</head>
<body class="hb" data-hb-kind="do" data-hb-autoplay>
<nav class="hb-bar" aria-label="Animation Handbook">
  <a class="hb-home" href="../../../"><svg class="hb-mark" viewBox="0 0 32 32" aria-hidden="true"><g class="g"><circle cx="11.16" cy="20.84" r="6.1"/><circle cx="15.12" cy="16.88" r="6.1"/><circle cx="18.51" cy="13.49" r="6.1"/></g><circle class="b" cx="21.2" cy="10.8" r="6.6"/></svg><span>Animation Handbook</span></a>
  <span class="hb-pager"><a href="../morphing-blob/" rel="prev" aria-label="Previous: Morphing Blob"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m15 18-6-6 6-6"/></svg><span><span class="hb-dir">Previous: </span>Morphing Blob</span></a><a href="../carousel-3d/" rel="next" aria-label="Next: 3D Carousel"><span><span class="hb-dir">Next: </span>3D Carousel</span><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m9 18 6-6-6-6"/></svg></a></span>
  <a class="hb-star" href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener" aria-label="Star on GitHub"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/></svg><span>Star on GitHub</span></a>
</nav>
<main class="hb-page">
  <header class="hb-head">
    <p class="hb-cat">06.18 · 3D &amp; Advanced</p>
    <h1>3D Flip Card</h1>
    <p class="hb-lede">A card turns over in 3D to show its back. Best for profile and product cards.</p>
  </header>

  <section class="hb-step hb-watch" aria-labelledby="hb-watch-title">
    <div class="hb-step-head">
      <span class="hb-num" aria-hidden="true">1</span>
      <div><h2 id="hb-watch-title">Click it</h2><p>Click or tap the card to turn it over, or press Show me.</p></div>
    </div>
    <div class="seg hb-modes" role="group" aria-label="What the box shows" data-hb-modes>
      <button type="button" data-hb-mode="normal" class="on" aria-pressed="true">Normal</button>
      <button type="button" data-hb-mode="inside" aria-pressed="false">See inside</button>
      <button type="button" data-hb-mode="compare" aria-pressed="false">Compare</button>
    </div>
    <div class="stage" id="stage">
      <div class="half real" id="half"><div class="tilt" id="tilt">
        <div class="card" id="card" tabindex="0" role="button" aria-pressed="false">
          <div class="face front">
            <div class="avatar">AV</div>
            <div class="name">Ava Reyes</div>
            <div class="role">Motion Engineer</div>
            <div class="hint">Tap or click to flip →</div>
          </div>
          <div class="face back">
            <div class="over">Details</div>
            <div class="rows">
              <div class="row"><span>Team</span><span>Interface Systems</span></div>
              <div class="row"><span>Location</span><span>Lisbon</span></div>
              <div class="row"><span>Focus</span><span>CSS 3D · WebGL</span></div>
              <div class="row"><span>Joined</span><span>2021</span></div>
            </div>
            <div class="hint">← Flip back</div>
          </div>
        </div>
      </div></div>
      <span class="cap cmp-name" data-hb-caption>Back shows through</span>
      <span class="cap cmp-name two" data-hb-caption>Back hidden</span>
      <span class="cap in-cap" data-hb-caption>Two faces, back to back (pulled apart here)</span>
      <span class="cap in-cap" data-hb-caption>The back starts turned away</span>
      <span class="cap in-cap" data-hb-caption>Dashed: a face pointing away is hidden</span>
      <span class="cap in-cap" data-hb-caption>Turns on this line in about two thirds of a second</span>
      <svg class="lead" aria-hidden="true"><path/><path/><path/><path/><circle r="3"/><circle r="3"/><circle r="3"/><circle r="3"/></svg>
    </div>
    <div class="hb-player">
      <button class="hb-play" type="button" id="btn-demo" data-hb-demo><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z"/></svg>Show me</button>
      <button class="hb-play" type="button" id="btn-reset" data-hb-reset><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/></svg>Reset</button>
      <label class="hb-toggle"><input class="hb-switch" type="checkbox" role="switch" id="slow-tog" data-hb-slowmo="css" autocomplete="off"><span>Slow motion</span></label>
    </div>
    <div class="hb-mode-notes" aria-live="polite">
      <p data-hb-for="inside" hidden>Inside, the two faces are pulled apart: the back starts turned away, the card turns around the gold line, and the face pointing away is hidden (dashed). Click the card or press Show me.</p>
      <p data-hb-for="compare" hidden>Back shows through: without hiding the face pointing away, the back covers the front, mirrored until it turns; Back hidden: each face shows only from its own side. Click the card or press Show me.</p>
    </div>
  </section>

  <section class="hb-step hb-try" aria-labelledby="hb-try-title">
    <div class="hb-step-head">
      <span class="hb-num" aria-hidden="true">2</span>
      <div><h2 id="hb-try-title">Try it</h2><p>Change a setting, then try it again or press Show me.</p></div>
    </div>
    <div class="hb-settings">
      <div class="hb-setting">
        <p class="hb-setting-name" id="axis-lbl">Flip direction</p>
        <div class="seg" id="axis-seg" role="group" aria-labelledby="axis-lbl">
          <button type="button" data-axis="y" class="on" aria-pressed="true">Sideways</button>
          <button type="button" data-axis="x" aria-pressed="false">Up and over</button>
        </div>
        <p class="hb-hint">Sideways turns like a page; up and over like a flap.</p>
      </div>
      <div class="hb-setting">
        <p class="hb-setting-name" id="speed-lbl">Speed</p>
        <div class="seg" id="speed-seg" role="group" aria-labelledby="speed-lbl">
          <button type="button" data-ms="1000" aria-pressed="false">Slow</button>
          <button type="button" data-ms="650" class="on" aria-pressed="true">Normal</button>
          <button type="button" data-ms="400" aria-pressed="false">Fast</button>
        </div>
        <p class="hb-hint">How long one turn takes.</p>
      </div>
      <div class="hb-setting">
        <p class="hb-setting-name" id="depth-lbl">3D depth</p>
        <div class="seg" id="depth-seg" role="group" aria-labelledby="depth-lbl">
          <button type="button" data-px="2000" aria-pressed="false">Subtle</button>
          <button type="button" data-px="1200" class="on" aria-pressed="true">Medium</button>
          <button type="button" data-px="600" aria-pressed="false">Strong</button>
        </div>
        <p class="hb-hint">Strong looks closer and more dramatic.</p>
      </div>
    </div>
    <details class="hb-options">
      <summary><span class="hb-more-label">More options</span><span class="hb-less">Fewer options</span><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg></summary>
      <div class="hb-settings">
        <div class="hb-setting">
          <label class="hb-switch-row"><span>Flips on hover</span><input class="hb-switch" type="checkbox" role="switch" id="hover-tog" autocomplete="off"></label>
          <p class="hb-hint">Pointing flips it; a tap still flips it on phones.</p>
        </div>
        <div class="hb-setting">
          <p class="hb-setting-name" id="tilt-lbl">Tilt toward the pointer</p>
          <div class="seg" id="tilt-seg" role="group" aria-labelledby="tilt-lbl">
            <button type="button" data-deg="0" aria-pressed="false">Off</button>
            <button type="button" data-deg="10" class="on" aria-pressed="true">Gentle</button>
            <button type="button" data-deg="18" aria-pressed="false">Strong</button>
          </div>
          <p class="hb-hint">The card leans toward a hovering pointer.</p>
        </div>
      </div>
    </details>
  </section>

  <section class="hb-step hb-prompt-step" aria-labelledby="hb-prompt-title">
    <div class="hb-step-head">
      <span class="hb-num" aria-hidden="true">3</span>
      <div><h2 id="hb-prompt-title">Copy the prompt</h2><p>Paste it into an AI assistant such as ChatGPT, Claude or Cursor to build this in your own project.</p></div>
    </div>
    <div class="hb-card">
      <p class="hb-prompt">Add a 3D flip to [the card you want to turn over]. Place the front and back faces in the same spot, turn the back face around so it faces away, and hide whichever face points away from the viewer. Clicking, tapping or pressing Enter turns the card over in 3D to show its back, and again to show its front. Give the card's container a 3D perspective so the turn has depth. When the settings include it, pointing at the card can flip it too, and the card can lean toward a hovering pointer. If the visitor has reduced motion turned on, swap the faces with a quick fade instead of turning. Match the settings listed below.</p>
      <div class="hb-chips-box" hidden>
        <p class="hb-chips-title">Your settings</p>
        <ul class="hb-chips"></ul>
      </div>
      <div class="hb-copy-row">
        <button class="hb-copy" type="button"><svg class="hb-ic hb-i-copy" viewBox="0 0 24 24" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg><svg class="hb-ic hb-i-done" viewBox="0 0 24 24" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg><span class="hb-copy-label" aria-live="polite">Copy prompt</span></button>
        <p class="hb-hint">Replace the words in brackets with your own element. Your settings are added at the end.</p>
      </div>
    </div>
    <div class="hb-star-row"><p>Free and open source. If this helped, a star on GitHub helps other people find it.</p><a class="hb-star-btn" href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/></svg>Star on GitHub</a></div>
  </section>

  <section class="hb-about" aria-labelledby="hb-what-title">
    <div class="hb-what">
      <h2 id="hb-what-title">What it is</h2>
      <div class="hb-what-text"><p>The full explanation is in <a href="README.md">README.md</a>.</p></div>
    </div>
    <div class="hb-fit">
      <h2>Good for</h2>
      <ul class="hb-tags hb-good"><li>Profile cards</li><li>Product cards</li><li>Flashcards</li><li>Quiz answers</li></ul>
      <h3>Avoid on</h3>
      <ul class="hb-tags hb-avoid"><li>Long text</li><li>Key information</li></ul>
    </div>
  </section>

  <section class="hb-related" aria-labelledby="hb-related-title" hidden>
    <h2 id="hb-related-title">Similar animations</h2>
    <div class="hb-rel-list"></div>
  </section>
</main>
<footer class="hb-foot"><span>Animation Handbook</span><a href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener">Source on GitHub</a><a href="#top">Back to top ↑</a></footer>
<script>
  const stage=document.getElementById('stage');
  const tilt=document.getElementById('tilt');
  const card=document.getElementById('card');
  const slowTog=document.getElementById('slow-tog');
  const root=document.documentElement.style;
  const reduce=matchMedia('(prefers-reduced-motion:reduce)');
  const canHover=matchMedia('(hover:hover)');
  const FLAT='rotateX(0deg) rotateY(0deg)';
  let trigger='click',maxTilt=10,flipMs=650,runTimer=0;
  // See inside and Compare. Compare's first half is a copy of the tilt and card, made once: no ids, no focus, hidden from screen
  // readers and inert. It follows the real card's classes and the tilt's lean, so a click, Show me, Reset, a hover or a lean on the
  // real card reaches both, and the turn runs by the same transition.
  const half=document.getElementById('half');
  const copy=half.cloneNode(true),copyCard=copy.querySelector('.card'),copyTilt=copy.querySelector('.tilt');
  copy.classList.replace('real','copy');
  [copy,...copy.querySelectorAll('*')].forEach(n=>{
    ['id','tabindex','role'].forEach(a=>n.removeAttribute(a));
    [...n.attributes].forEach(a=>{if(a.name.startsWith('aria-'))n.removeAttribute(a.name)});
  });
  copy.setAttribute('aria-hidden','true');copy.inert=true;half.before(copy);
  card.insertAdjacentHTML('beforeend','<i class="dash d-f" aria-hidden="true"></i><i class="dash d-b" aria-hidden="true"></i>');
  tilt.insertAdjacentHTML('beforeend','<i class="axis" aria-hidden="true"></i><svg class="arrow" viewBox="0 0 40 24" aria-hidden="true"><path d="M5 22C5 5 33 5 33 20M28.5 15.5L33 21l4.5-5.5"/></svg>');
  const axis=tilt.querySelector('.axis'),arrow=tilt.querySelector('.arrow'),lead=stage.querySelector('.lead');
  function syncCopy(){copyCard.className=card.className;copyTilt.className=tilt.className;copyTilt.style.transform=tilt.style.transform;}
  new MutationObserver(syncCopy).observe(card,{attributes:true,attributeFilter:['class']});
  new MutationObserver(syncCopy).observe(tilt,{attributes:true,attributeFilter:['class','style']});
  let mode='normal',cs=1;

  function setFlipped(on){
    card.classList.toggle('flipped',on);
    card.setAttribute('aria-pressed',on?'true':'false');
    if(mode!=='normal'&&reduce.matches)draw();
  }
  function toggle(){setFlipped(!card.classList.contains('flipped'));}

  // Show me: one click's worth. The card turns to its back, rests there for 1.2 s and turns back. Slow motion stretches the
  // turns (the wait for the first one is three times as long), never the rest. A run starts from the front: a card that
  // shows its back is put there without turning. The one timer is the run's only handle; anything can stop it.
  function stopRun(){clearTimeout(runTimer);runTimer=0;}
  function toFront(){
    if(!card.classList.contains('flipped'))return;
    // The card turns by its own transition, and under reduced motion the faces fade instead: hold both for this one change
    const held=[card,copyCard,...card.querySelectorAll('.face'),...copyCard.querySelectorAll('.face')];
    held.forEach(el=>el.style.setProperty('transition','none','important'));
    setFlipped(false);syncCopy();void card.offsetWidth;void copyCard.offsetWidth;
    held.forEach(el=>el.style.removeProperty('transition'));
  }
  document.getElementById('btn-demo').addEventListener('click',()=>{
    stopRun();hovering=false;toFront();setFlipped(true);
    runTimer=setTimeout(()=>{runTimer=0;setFlipped(false);},flipMs*(slowTog.checked?3:1)+1200);
  });
  document.getElementById('btn-reset').addEventListener('click',()=>{
    stopRun();hovering=false;setFlipped(false);tilt.style.transform=FLAT;
  });
  // The visitor pressed, typed, scrolled or touched inside the stage: only a run that is under way stops, and the card stays
  // as it is. The click, tap or key that comes with it then turns the card as usual.
  document.addEventListener('hb:input',()=>{if(runTimer)stopRun();});

  // Click or tap: gate on the pointer that actually acted, not on the device, since a touch laptop reports hover:hover and a
  // media query alone would leave a tap dead there. With Flips on hover a tap still turns the card.
  let lastPointer='mouse';
  card.addEventListener('pointerdown',e=>{lastPointer=e.pointerType;});
  card.addEventListener('click',()=>{if(trigger==='click'||lastPointer==='touch'||!canHover.matches)toggle();});
  // Keyboard — the card is reachable and operable without a pointer
  card.addEventListener('keydown',e=>{
    if((e.key==='Enter'||e.key===' ')&&!e.repeat){e.preventDefault();toggle();}
  });
  // Flips on hover (pointer-capable devices only): the pointer is over the card when it is over the place the card sits in, not
  // over its turning outline, which narrows past a resting pointer and would send the card back and forth. A pointer that goes on
  // or off the card takes over from a run.
  let hovering=false;
  function hoverFlip(on,trusted){
    if(on===hovering)return;
    hovering=on;
    if(trusted)stopRun();
    setFlipped(on);
  }
  // The place the card sits in: the stage's middle, or in Compare the middle of a half (below its name)
  function frame(h){
    const r=(h||stage).getBoundingClientRect(),t=h?parseFloat(getComputedStyle(h).paddingTop):0;
    return{left:r.left,top:r.top+t,width:r.width,height:r.height-t};
  }
  function overCard(e,r){
    const k=mode==='compare'?cs:1;
    return Math.abs(e.clientX-(r.left+r.width/2))<=card.offsetWidth*k/2&&Math.abs(e.clientY-(r.top+r.height/2))<=card.offsetHeight*k/2;
  }

  // Cursor-driven idle 3D tilt and Flips on hover, both via Pointer Events
  stage.addEventListener('pointermove',e=>{
    if(e.pointerType==='touch')return;
    const cmp=mode==='compare',r=frame(cmp?half:null);
    if(trigger==='hover')hoverFlip(overCard(e,r),e.isTrusted);
    if(reduce.matches||!canHover.matches||maxTilt===0)return;
    // in Compare the lean follows the pointer across the half it is over
    const l=cmp&&e.clientX<half.getBoundingClientRect().left?frame(copy):r;
    const x=Math.max(-.5,Math.min(.5,(e.clientX-l.left)/l.width-.5));
    const y=Math.max(-.5,Math.min(.5,(e.clientY-l.top)/l.height-.5));
    tilt.classList.add('tracking');
    tilt.style.transform=`rotateX(${(-y*maxTilt).toFixed(2)}deg) rotateY(${(x*maxTilt).toFixed(2)}deg)`;
  });
  stage.addEventListener('pointerleave',e=>{
    if(trigger==='hover'&&e.pointerType!=='touch')hoverFlip(false,e.isTrusted);
    tilt.classList.remove('tracking');
    tilt.style.transform=FLAT;
  });

  function choices(id,pick){
    const buttons=document.querySelectorAll('#'+id+' button');
    buttons.forEach(b=>b.addEventListener('click',()=>{
      buttons.forEach(x=>{x.classList.toggle('on',x===b);x.setAttribute('aria-pressed',String(x===b))});
      pick(b.dataset);
    }));
  }
  choices('axis-seg',d=>{card.classList.toggle('axis-x',d.axis==='x');stage.classList.toggle('xturn',d.axis==='x');draw();});
  choices('speed-seg',d=>{flipMs=+d.ms;root.setProperty('--flip-dur',flipMs+'ms');draw();});
  choices('depth-seg',d=>{root.setProperty('--perspective',d.px+'px');draw();});
  choices('tilt-seg',d=>{maxTilt=+d.deg;if(maxTilt===0)tilt.style.transform=FLAT;});
  document.getElementById('hover-tog').addEventListener('change',e=>{
    trigger=e.target.checked?'hover':'click';
    hovering=false;
    if(e.target.checked)setFlipped(false);
  });
  // The two views, drawn from the page's own numbers: the card's measured size, the stage's perspective and, for the caption that
  // says how long a turn takes, the speed and Slow motion.
  // See inside turns the whole card, pulled apart, three quarters toward the viewer (VX, VY) and moves each face GAP of the card's
  // width off the turning line. The captions are placed from the same projection the browser applies, so they point at what they name.
  const VX=12,VY=-28,GAP=.2,AW=40,AH=24;
  const notes={inside:document.querySelector('[data-hb-for="inside"]'),compare:document.querySelector('[data-hb-for="compare"]')};
  const NOTE={inside:notes.inside.textContent,compare:notes.compare.textContent};
  const STILL={inside:['Shown still, a third of the way through a turn: the two faces are pulled apart, the back starts turned away, and the face pointing away is hidden (dashed).',
      'Shown still, a third of the way back through a turn: the two faces are pulled apart, the back now faces you, and the face pointing away is hidden (dashed).'],
    compare:['Shown still: Back shows through has the back on top of the front, mirrored, since nothing hides the face pointing away; Back hidden shows the front.',
      'Shown still, turned over: both cards show the details facing the right way. Turn it back, and Back shows through covers its front with the back, mirrored.']};
  function say(el,t){if(el.textContent!==t)el.textContent=t}
  const SECONDS=[[500,'under half a second'],[800,'about two thirds of a second'],[1100,'about a second'],[1500,'just over a second'],[2500,'about two seconds']];
  const seconds=ms=>(SECONDS.find(([m])=>ms<m)||[0,'about three seconds'])[1];
  function draw(){
    if(mode!=='inside'){half.style.transform=half.style.translate='';stage.style.removeProperty('--gap')}
    if(mode!=='compare')[half,copy].forEach(h=>h.style.removeProperty('--cs'));
    if(mode==='compare')sizeCompare();
    if(mode==='inside')placeInside();
    if(notes[mode])say(notes[mode],reduce.matches?STILL[mode][+card.classList.contains('flipped')]:NOTE[mode]);
  }
  // Compare: each card keeps its 156 x 218 layout and is scaled to what its half leaves (the half names sit above the cards)
  function sizeCompare(){
    cs=Math.min(1.2,(half.clientWidth-12)/156,(half.clientHeight-parseFloat(getComputedStyle(half).paddingTop)-10)/218);
    [half,copy].forEach(h=>h.style.setProperty('--cs',cs));
  }
  const rotate=(p,x,d)=>{const c=Math.cos(d*Math.PI/180),s=Math.sin(d*Math.PI/180);return x?[p[0],p[1]*c-p[2]*s,p[1]*s+p[2]*c]:[p[0]*c+p[2]*s,p[1],-p[0]*s+p[2]*c]};
  function placeInside(){
    const W=stage.clientWidth,H=stage.clientHeight,cw=card.offsetWidth,ch=card.offsetHeight,xt=stage.classList.contains('xturn');
    const P=parseFloat(getComputedStyle(stage).perspective)||1200,rm=reduce.matches,vy=rm?0:VY,turn=rm?(card.classList.contains('flipped')?120:60):0;
    const g=cw*GAP,ext=Math.max(10,ch*.05),caps=[...stage.querySelectorAll('.in-cap')];
    say(caps[3],'Turns on this line in '+seconds(flipMs*(slowTog.checked?3:1)));
    // a point of the card (x right, y down, z toward the viewer; t: it turns with the card) as the viewer sees it, from the stage's middle
    const pr=(x,y,z,s,t)=>{let p=[x*s,y*s,z*s];if(t&&turn)p=rotate(p,xt,turn);p=rotate(rotate(p,0,vy),1,VX);const k=P/(P-p[2]);return[p[0]*k,p[1]*k]};
    // the gold line and its arrow stand in front of the faces (z), shifted so that, seen from here, they run through the card's middle
    const z=g+2,ox=xt?0:-z*Math.tan(vy*Math.PI/180),oy=xt?z*Math.cos(vy*Math.PI/180)*Math.tan(VX*Math.PI/180):0,L=xt?cw/2+ext:ch/2+ext;
    const on=(x,y)=>[x+ox,y+oy,z,0],e=xt?on(-L,0):on(0,-L),f=[[-1,-1],[1,-1],[1,1],[-1,1]].map(([a,b])=>[a*cw/2,b*ch/2]);
    const ab=xt?[-L-AH/2-2,-AW-4,-L+AH/2-2,-4]:[8,-L-AH/2-2,8+AW,-L+AH/2-2];
    const pts=[...f.map(a=>[...a,g,1]),...f.map(a=>[...a,-g,1]),e,xt?on(L,0):on(0,L),on(ab[0],ab[1]),on(ab[2],ab[1]),on(ab[0],ab[3]),on(ab[2],ab[3])];
    const box=s=>{const q=pts.map(a=>pr(a[0],a[1],a[2],s,a[3])),x=q.map(a=>a[0]),y=q.map(a=>a[1]);return[Math.min(...x),Math.min(...y),Math.max(...x),Math.max(...y)]};
    const nat=[];caps.forEach((c,i)=>{c.style.cssText='left:0;top:0';nat[i]=[c.offsetWidth,c.offsetHeight]});
    // a caption that is wider than its room wraps to it
    const fit=(i,room)=>{if(nat[i][0]>room)caps[i].style.cssText=`left:0;top:0;white-space:normal;width:${room}px`;nat[i]=[caps[i].offsetWidth,caps[i].offsetHeight]};
    // room for a column of captions each side of the drawing, else captions above and below it
    const b1=box(1),bh=b1[3]-b1[1],s1=Math.min(1,(H-12)/bh),side=(W-(b1[2]-b1[0])*s1)/2>=150;
    if(!side)caps.forEach((c,i)=>fit(i,W-12));
    const top=nat[3][1]+nat[0][1]+14,bot=nat[1][1]+nat[2][1]+14;
    const s=side?s1:Math.min(1,(H-top-bot)/bh,(W-12)/(b1[2]-b1[0])),b=box(s);
    const tx=-(b[0]+b[2])/2,ty=(side?0:(top-bot)/2)-(b[1]+b[3])/2;
    half.style.transform=`rotateX(${VX}deg) rotateY(${vy}deg) scale3d(${s},${s},${s})`;half.style.translate=`${tx}px ${ty}px`;
    stage.style.setProperty('--gap',g+'px');
    axis.style.width=(xt?2*L:3)+'px';axis.style.height=(xt?3:2*L)+'px';axis.style.translate=`calc(-50% + ${ox}px) calc(-50% + ${oy}px) ${z}px`;
    arrow.style.translate=`${(ab[0]+ab[2]-AW)/2+ox}px ${(ab[1]+ab[3]-AH)/2+oy}px ${z}px`;
    lead.style.visibility=side?'':'hidden';
    if(!side){
      let y=6;[3,0].forEach(i=>{caps[i].style.left=(W-nat[i][0])/2+'px';caps[i].style.top=y+'px';y+=nat[i][1]+4});
      y=H-6;[2,1].forEach(i=>{y-=nat[i][1];caps[i].style.left=(W-nat[i][0])/2+'px';caps[i].style.top=y+'px';y-=4});
      return;
    }
    // what each caption points at: the front's left edge, the back's top right corner, its right edge, and the line's end
    const at=[[-cw/2,xt?ch*.3:0,g,1],[cw/2,-ch/2,-g,1],[cw/2,ch/4,-g,1],e].map(a=>{const q=pr(a[0],a[1],a[2],s,a[3]);return[W/2+tx+q[0],H/2+ty+q[1]]});
    const cols=[[],[]];
    at.forEach((a,i)=>cols[+(a[0]>W/2)].push(i));
    cols.forEach((col,c)=>{
      const room=c?W-6-(W/2+(b[2]-b[0])/2+16):W/2-(b[2]-b[0])/2-16-6,items=col.sort((i,j)=>at[i][1]-at[j][1]);
      items.forEach(i=>fit(i,room));
      let end=0;const ys=items.map(i=>{const y=Math.max(at[i][1]-nat[i][1]/2,end+6,6);end=y+nat[i][1];return y}),up=Math.max(0,end-(H-6));
      items.forEach((i,k)=>{
        const w=nat[i][0],h=nat[i][1],yy=Math.max(6,ys[k]-up),xx=c?W/2+(b[2]-b[0])/2+16:W/2-(b[2]-b[0])/2-16-w;
        caps[i].style.left=xx+'px';caps[i].style.top=yy+'px';
        lead.children[i].setAttribute('d',`M${c?xx:xx+w} ${yy+h/2}L${at[i][0]} ${at[i][1]}`);
        lead.children[i+4].setAttribute('cx',at[i][0]);lead.children[i+4].setAttribute('cy',at[i][1]);
      });
    });
  }
  // A mode press draws the mode at once and nothing else: the shared script plays Show me after it (never under reduced motion)
  document.addEventListener('hb:mode',e=>{mode=e.detail.mode;if(mode==='compare')syncCopy();draw()});
  addEventListener('resize',draw);
  reduce.addEventListener('change',draw);
  slowTog.addEventListener('change',draw);
  document.fonts.ready.then(draw);
</script>
</body>
</html>