About this UI Snippet
Flexbox Alignment Game — Ghost-Layer Targets, Position-Based Win Detection & Live Generated CSS

Flexbox is learned by watching things move, not by reading property tables, and the fastest way to build that intuition is a tight loop: change one value, see the layout react immediately, and know instantly whether the result is right. This snippet is a playable flexbox trainer built around exactly that loop — a stage with dashed target slots, a row of chips for flex-direction, justify-content and align-items, and balls that animate to their new positions the moment a value changes, with the equivalent CSS rule printed live underneath.
Targets drawn by flexbox itself, not by hardcoded coordinates
The stage holds two absolutely positioned layers of identical size. The lower one, the ghost layer, is a flex container filled with dashed .fx-slot circles and given the level's solution styles; the upper one holds the real .fx-ball elements and receives whatever the player has selected. Because the target positions are produced by applying real flex properties to a real container rather than by storing pixel coordinates, they stay correct at every stage width, on every device, and after any resize — there is no coordinate table to fall out of sync with the CSS. Adding a level means writing one solution object, not measuring anything.
Winning is positional, so alternative routes are accepted
isSolved() never compares the player's chosen property values against the level's solution object. It measures both layers with getBoundingClientRect(), reduces each element to its centre point, and requires every ball centre to sit within a six-pixel tolerance of some slot centre. That means any combination of properties that genuinely lands the balls on their targets counts as a win — which is the honest definition of "did you solve the layout" and prevents the game from teaching one memorised answer per level. The tolerance exists because flex distribution produces sub-pixel fractional positions that will not compare exactly equal, and because a strict equality check would fail intermittently at certain container widths.
Measuring at the right moment
Setting justifyContent on the live layer changes layout synchronously, but the check runs inside a requestAnimationFrame callback so measurement happens after the browser has settled the new layout rather than in the middle of the same task that mutated it. The balls animate to their new positions with a springy cubic-bezier transition, but the check deliberately does not wait for that animation: getBoundingClientRect() on a transitioning element returns its live interpolated box, so waiting for the transition would only delay the verdict, while measuring the settled layout box immediately is both correct and instant.
Generated CSS as the real reward
Every change re-renders a code panel containing the exact rule the player has constructed — display: flex plus the three chosen properties, formatted as copy-ready CSS. This is what converts play into transferable knowledge: the player ends each level looking at the declaration block that produced the layout they just built, in the same syntax they will type into a real stylesheet.
State kept in one object, chips derived from it
A single state object holds the three current values, and syncChips() re-derives which chip in each group is active by comparing chip.dataset.value against state[prop]. Nothing tracks selection independently in the DOM, so the visual state of the controls cannot drift from the styles actually applied to the layer — the same one-way data-flow discipline a framework would enforce, implemented in a dozen lines of vanilla JavaScript. A move counter increments only when a chip changes the value rather than on every click, so re-clicking the already-active option costs nothing.
What's included
Features
Step by step
How to Use
- 1Read the goal and find the dashed slotsEach level states its objective in plain English and draws dashed circles where the balls need to end up. Those slots are positioned by real flex properties on a hidden ghost layer, so they sit correctly at any stage size.
- 2Pick a flex-directionSwitching between row and column changes which axis is the main axis — and therefore what justify-content and align-items each control. Levels 4 through 6 only solve in column mode, which is the fastest way to internalise the axis swap.
- 3Choose justify-content and align-itemsEvery chip applies its value to the live layer immediately and the balls animate to their new positions with a spring transition, so you see the effect of a single property change in isolation.
- 4Read the generated CSSThe dark code panel always shows the exact rule you have built — display: flex plus your three current values — formatted as a copy-ready declaration block, so the layout and the syntax stay connected.
- 5Land every ball to advanceThe win check measures both layers with getBoundingClientRect() and requires each ball centre within six pixels of a slot centre. Any property combination that genuinely lands them counts, and the balls turn green when the level is solved.
- 6Watch your move countThe counter increments only when a chip actually changes a value, not on every click. Clearing all six levels in as few moves as possible is the natural replay goal once you know the properties.
Real-world uses
Common Use Cases
Got questions?
Frequently Asked Questions
Where they end up. isSolved() measures both layers with getBoundingClientRect(), reduces every element to its centre, and requires each ball centre within six pixels of a slot centre. The level solution object is used only to style the ghost targets, never compared against your selections — so any combination that lands the balls correctly is accepted.
Flex distribution routinely produces fractional pixel positions (a container width that does not divide evenly across items, for example), so ball and slot centres would rarely be exactly equal even when the layout is visually identical. A small tolerance absorbs that sub-pixel noise while still being far tighter than the gap between any two distinct alignment values.
Setting a style property and reading geometry in the same task can measure a layout the browser has not finished settling. Deferring the read to the next animation frame guarantees the new layout is in place. Note the check does not wait for the CSS transition to finish — getBoundingClientRect() returns the interpolated box mid-transition, so waiting would only delay the verdict without changing it.
Push an object onto the LEVELS array with three keys: balls (how many items), goal (the plain-English instruction), and solution (an object with flexDirection, justifyContent and alignItems). The ghost layer is styled with that solution object, so the dashed targets position themselves — you never need to compute or store coordinates.
Yes. Keep the LEVELS array in a module, hold the three property values in component state, and bind them straight to the live layer's style object so the framework handles the style updates. Put the getBoundingClientRect() comparison in an effect that runs after the style change commits — useEffect in React, watch plus nextTick in Vue, ngAfterViewChecked or a signal effect in Angular — using refs to both layers rather than getElementById, and remember to remove the resize listener on unmount.
Copy & paste
Source Code
<div class="demo-wrap">
<div class="fx-game">
<div class="fx-head">
<div class="fx-meta"><span class="fx-label">Level</span><span class="fx-value" id="fxLevel">1 / 6</span></div>
<div class="fx-meta fx-right"><span class="fx-label">Moves</span><span class="fx-value" id="fxMoves">0</span></div>
</div>
<p class="fx-goal" id="fxGoal">Land every ball inside its dashed outline.</p>
<div class="fx-stage" id="fxStage">
<div class="fx-layer fx-ghost" id="fxGhost"></div>
<div class="fx-layer fx-live" id="fxLive"></div>
</div>
<div class="fx-controls" id="fxControls">
<div class="fx-group" data-prop="flexDirection">
<span class="fx-prop">flex-direction</span>
<div class="fx-chips">
<button class="fx-chip is-on" data-value="row">row</button>
<button class="fx-chip" data-value="column">column</button>
</div>
</div>
<div class="fx-group" data-prop="justifyContent">
<span class="fx-prop">justify-content</span>
<div class="fx-chips">
<button class="fx-chip is-on" data-value="flex-start">flex-start</button>
<button class="fx-chip" data-value="center">center</button>
<button class="fx-chip" data-value="flex-end">flex-end</button>
<button class="fx-chip" data-value="space-between">space-between</button>
</div>
</div>
<div class="fx-group" data-prop="alignItems">
<span class="fx-prop">align-items</span>
<div class="fx-chips">
<button class="fx-chip is-on" data-value="flex-start">flex-start</button>
<button class="fx-chip" data-value="center">center</button>
<button class="fx-chip" data-value="flex-end">flex-end</button>
</div>
</div>
</div>
<pre class="fx-code" id="fxCode"></pre>
<p class="fx-status" id="fxStatus">Pick values and watch the balls move.</p>
</div>
</div>* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: system-ui, -apple-system, sans-serif; background: #f1f5f9; min-height: 100vh; }
.demo-wrap { display: flex; align-items: center; justify-content: center; min-height: 100vh; padding: 28px 16px; }
.fx-game {
width: 100%; max-width: 440px; padding: 20px;
background: #fff; border: 1px solid #e2e8f0; border-radius: 16px;
display: flex; flex-direction: column; gap: 14px;
box-shadow: 0 12px 32px rgba(15,23,42,0.08);
}
.fx-head { display: flex; justify-content: space-between; }
.fx-meta { display: flex; flex-direction: column; gap: 2px; }
.fx-right { align-items: flex-end; }
.fx-label { font-size: 10px; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; color: #94a3b8; }
.fx-value { font-size: 16px; font-weight: 800; color: #0f172a; }
.fx-goal {
font-size: 13.5px; font-weight: 600; color: #334155; line-height: 1.5;
background: #f8fafc; border-left: 3px solid #0ea5e9; border-radius: 0 8px 8px 0; padding: 10px 12px;
}
.fx-stage {
position: relative; height: 190px; border-radius: 12px;
background: repeating-linear-gradient(45deg, #f8fafc 0 10px, #f1f5f9 10px 20px);
border: 2px solid #e2e8f0; overflow: hidden;
}
.fx-layer { position: absolute; inset: 0; display: flex; padding: 14px; gap: 10px; }
.fx-ghost { pointer-events: none; }
.fx-ball {
width: 42px; height: 42px; border-radius: 50%; flex: 0 0 auto;
background: #0ea5e9; box-shadow: 0 4px 12px rgba(14,165,233,0.35);
transition: all 0.35s cubic-bezier(0.34, 1.4, 0.64, 1);
display: flex; align-items: center; justify-content: center;
color: #fff; font-size: 13px; font-weight: 800;
}
.fx-slot {
width: 42px; height: 42px; border-radius: 50%; flex: 0 0 auto;
border: 2px dashed #94a3b8; background: rgba(148,163,184,0.12);
}
.fx-live.solved .fx-ball { background: #22c55e; box-shadow: 0 4px 14px rgba(34,197,94,0.4); }
.fx-controls { display: flex; flex-direction: column; gap: 10px; }
.fx-group { display: flex; flex-direction: column; gap: 5px; }
.fx-prop { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 11px; font-weight: 700; color: #64748b; }
.fx-chips { display: flex; flex-wrap: wrap; gap: 5px; }
.fx-chip {
padding: 6px 10px; border-radius: 7px; border: 1.5px solid #e2e8f0; background: #f8fafc;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 11px; font-weight: 600;
color: #475569; cursor: pointer; transition: all 0.12s;
}
.fx-chip:hover { border-color: #0ea5e9; color: #0ea5e9; }
.fx-chip.is-on { background: #0ea5e9; border-color: #0ea5e9; color: #fff; }
.fx-code {
background: #0f172a; border-radius: 10px; padding: 12px; color: #cbd5e1;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 11.5px; line-height: 1.6;
white-space: pre; overflow-x: auto;
}
.fx-status { font-size: 12px; font-weight: 600; color: #64748b; min-height: 18px; }
.fx-status.ok { color: #16a34a; }var LEVELS = [
{ balls: 3, goal: 'Push all three balls to the far end of the row.', solution: { flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'flex-start' } },
{ balls: 3, goal: 'Centre the row both horizontally and vertically.', solution: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center' } },
{ balls: 3, goal: 'Spread the balls edge to edge along the bottom.', solution: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-end' } },
{ balls: 2, goal: 'Stack them vertically, hugging the top-right corner.', solution: { flexDirection: 'column', justifyContent: 'flex-start', alignItems: 'flex-end' } },
{ balls: 3, goal: 'Stack them in a column, spread top to bottom, centred across.', solution: { flexDirection: 'column', justifyContent: 'space-between', alignItems: 'center' } },
{ balls: 2, goal: 'Column again — bottom of the stage, hard left.', solution: { flexDirection: 'column', justifyContent: 'flex-end', alignItems: 'flex-start' } },
];
var TOLERANCE = 6; // px of slop allowed between a ball centre and its slot centre
var ghost = document.getElementById('fxGhost');
var live = document.getElementById('fxLive');
var goalEl = document.getElementById('fxGoal');
var codeEl = document.getElementById('fxCode');
var statusEl = document.getElementById('fxStatus');
var levelEl = document.getElementById('fxLevel');
var movesEl = document.getElementById('fxMoves');
var index = 0;
var moves = 0;
var locked = false;
var state = { flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'flex-start' };
function level() { return LEVELS[index]; }
function applyStyles(el, styles) {
el.style.flexDirection = styles.flexDirection;
el.style.justifyContent = styles.justifyContent;
el.style.alignItems = styles.alignItems;
}
function fillLayer(el, count, cls, labelled) {
el.innerHTML = '';
for (var i = 0; i < count; i++) {
var node = document.createElement('div');
node.className = cls;
if (labelled) node.textContent = i + 1;
el.appendChild(node);
}
}
function renderCode() {
codeEl.textContent = '.container {\n display: flex;\n flex-direction: ' + state.flexDirection +
';\n justify-content: ' + state.justifyContent +
';\n align-items: ' + state.alignItems + ';\n}';
}
function syncChips() {
var groups = document.querySelectorAll('.fx-group');
Array.prototype.forEach.call(groups, function (group) {
var prop = group.dataset.prop;
Array.prototype.forEach.call(group.querySelectorAll('.fx-chip'), function (chip) {
chip.classList.toggle('is-on', chip.dataset.value === state[prop]);
});
});
}
function centres(layer) {
return Array.prototype.map.call(layer.children, function (el) {
var r = el.getBoundingClientRect();
return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
});
}
// Win check is positional, not property-based: every ball centre must sit
// within TOLERANCE of a slot centre, so any styles that land them count.
function isSolved() {
var balls = centres(live);
var slots = centres(ghost);
if (balls.length !== slots.length) return false;
return balls.every(function (b) {
return slots.some(function (s) {
return Math.abs(b.x - s.x) <= TOLERANCE && Math.abs(b.y - s.y) <= TOLERANCE;
});
});
}
function setStatus(msg, kind) {
statusEl.textContent = msg;
statusEl.className = 'fx-status' + (kind ? ' ' + kind : '');
}
function evaluate() {
// Wait a frame so the transition-independent layout is measurable.
requestAnimationFrame(function () {
if (locked) return;
if (!isSolved()) return;
locked = true;
live.classList.add('solved');
if (index === LEVELS.length - 1) {
setStatus('Solved in ' + moves + ' moves — all six levels cleared!', 'ok');
setTimeout(function () { index = 0; moves = 0; loadLevel(); }, 1800);
} else {
setStatus('Solved! Next level…', 'ok');
setTimeout(function () { index++; loadLevel(); }, 1000);
}
});
}
function loadLevel() {
var lv = level();
locked = false;
live.classList.remove('solved');
goalEl.textContent = lv.goal;
levelEl.textContent = (index + 1) + ' / ' + LEVELS.length;
movesEl.textContent = moves;
fillLayer(ghost, lv.balls, 'fx-slot', false);
fillLayer(live, lv.balls, 'fx-ball', true);
applyStyles(ghost, lv.solution);
state = { flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'flex-start' };
applyStyles(live, state);
syncChips();
renderCode();
setStatus('Pick values and watch the balls move.', '');
}
document.getElementById('fxControls').addEventListener('click', function (e) {
var chip = e.target.closest('.fx-chip');
if (!chip || locked) return;
var prop = chip.closest('.fx-group').dataset.prop;
if (state[prop] === chip.dataset.value) return;
state[prop] = chip.dataset.value;
moves++;
movesEl.textContent = moves;
applyStyles(live, state);
syncChips();
renderCode();
evaluate();
});
window.addEventListener('resize', function () { if (!locked) evaluate(); });
loadLevel();
/* wdp-share:start */
(function () {
var TITLE = 'Flexbox Alignment Game', URL = 'https://webdevpuneet.com/ui-snippets/flexbox-align-game/';
if (window.__wdpShare) return;
window.__wdpShare = true;
var blob = null, file = null, lastInfo = null;
/* ---- UI ---- */
var st = document.createElement('style');
st.textContent =
'.wdps-in,.wdps-btn,.wdps-box{touch-action:manipulation;-webkit-tap-highlight-color:transparent}.wdps-in{display:block;margin:12px auto 0;border:0;border-radius:12px;padding:11px 22px;font:800 15px/1 system-ui,sans-serif;background:#16a34a;color:#fff;cursor:pointer;box-shadow:0 3px 0 #11793a;pointer-events:auto;position:relative;z-index:5}' +
'.wdps-in:hover{background:#15803d}.wdps-in:active{transform:translateY(2px);box-shadow:0 1px 0 #11793a}' +
'.wdps-btn{position:fixed;right:12px;bottom:12px;z-index:2147483000;border:0;border-radius:99px;padding:9px 16px;font:700 13px/1 system-ui,sans-serif;background:#16a34a;color:#fff;cursor:pointer;box-shadow:0 3px 12px rgba(0,0,0,.3)}' +
'.wdps-btn.wdps-hot{animation:wdps-p 1.4s ease-in-out infinite}' +
'@keyframes wdps-p{0%,100%{box-shadow:0 0 0 0 rgba(22,163,74,.6),0 3px 12px rgba(0,0,0,.3)}50%{box-shadow:0 0 0 9px rgba(22,163,74,0),0 3px 12px rgba(0,0,0,.3)}}' +
'.wdps-btn:active{transform:translateY(1px)}' +
'.wdps-in[hidden],.wdps-btn[hidden],.wdps-box[hidden],.wdps-box [hidden]{display:none}' +
'.wdps-box{position:fixed;left:50%;bottom:12px;transform:translateX(-50%);z-index:2147483001;width:max-content;max-width:calc(100vw - 24px);box-sizing:border-box;background:#fff;color:#64748b;border:1px solid #d5e2ee;border-radius:12px;padding:8px 12px;font:700 12px/1.4 system-ui,sans-serif;box-shadow:0 8px 26px rgba(15,23,42,.25);display:flex;flex-wrap:wrap;gap:8px;align-items:center}' +
'.wdps-box button,.wdps-box a{border:1px solid #d5e2ee;background:#f8fafc;color:#1e293b;border-radius:99px;padding:5px 12px;font:700 12px system-ui,sans-serif;text-decoration:none;cursor:pointer}' +
'.wdps-box .wdps-x{border:0;background:none;font-size:19px;line-height:1;padding:0 4px;margin-left:auto;color:#475569}' +
'@media (max-width:700px){.wdps-box{width:calc(100vw - 24px);justify-content:center;padding:10px 12px}.wdps-box>span{width:100%;text-align:center}.wdps-box button,.wdps-box a{padding:9px 14px;font-size:13px}.wdps-box .wdps-x{position:absolute;top:4px;right:4px}.wdps-in{width:100%;max-width:320px}}';
document.head.appendChild(st);
var pill = document.createElement('button');
pill.type = 'button'; pill.className = 'wdps-btn'; pill.textContent = 'Share result';
var inl = document.createElement('button');
inl.type = 'button'; inl.className = 'wdps-in'; inl.textContent = 'Share result'; inl.hidden = true;
var box = document.createElement('div');
box.className = 'wdps-box'; box.hidden = true;
box.setAttribute('role', 'dialog'); box.setAttribute('aria-label', 'Share your result');
box.innerHTML =
'<span data-a="msg">Share your result:</span>' +
'<button type="button" data-a="copy">Copy image</button>' +
'<a data-a="dl" download="result.png">Download image</a>' +
'<button type="button" data-a="more" hidden>More…</button>' +
'<a data-a="wa" target="_blank" rel="noopener">WhatsApp</a>' +
'<a data-a="x" target="_blank" rel="noopener">X</a>' +
'<a data-a="fb" target="_blank" rel="noopener">Facebook</a>' +
'<button type="button" class="wdps-x" data-a="close" aria-label="Close share options">×</button>';
document.body.appendChild(box);
document.body.appendChild(pill);
function q(a) { return box.querySelector('[data-a="' + a + '"]'); }
function ours(el) { return el === inl || el === pill || !!el.closest('.wdps-box'); }
/* ---- reading the result from the screen ---- */
function shown(el) {
if (!el || !el.getClientRects().length) return false;
for (var n = el; n && n !== document.body; n = n.parentElement) {
var cs = getComputedStyle(n);
if (cs.display === 'none' || cs.visibility === 'hidden' || parseFloat(cs.opacity) < 0.1) return false;
if (n.hidden || n.getAttribute('aria-hidden') === 'true') return false;
}
return true;
}
function txt(el) { return (el.textContent || '').replace(/\s+/g, ' ').trim(); }
function sig(el) { return ((el.id || '') + ' ' + (typeof el.className === 'string' ? el.className : '')).toLowerCase(); }
var OUTCOME = /(you win|you won|win!|wins|victory|game over|time.?s up|cleared|complete|solved|defeat|you lose|you lost|lost|draw|crash|failed|success|congrat|score|result|finished|beat|all matched|well done|perfect|new best)/i;
var HEADSIG = /(title|headline|msg|message|banner|result|verdict|status)/;
var WIN = /(you win|you won|win!|wins|victory|cleared|complete|solved|success|congrat|beat|matched|perfect|new best|record)/i;
var LOSS = /(game over|time.?s up|defeat|you lose|you lost|lost|crash|failed|out of)/i;
var BOX = /(overlay|modal|banner|result|over|end|dialog|screen|popup|panel|card|finish|win)/;
function readResult() {
var head = '', sub = '', root = null, headEl = null;
var all = document.body.querySelectorAll('h1,h2,h3,h4,p,strong,div,span');
for (var i = 0; i < all.length && !head; i++) {
var el = all[i];
if (ours(el) || el.children.length > 2) continue;
if (!HEADSIG.test(sig(el))) continue;
/* a banner that holds its own title: use the title inside it instead */
var inner = false;
for (var c = 0; c < el.children.length; c++) if (HEADSIG.test(sig(el.children[c]))) inner = true;
if (inner) continue;
var t = txt(el);
if (t.length < 3 || t.length > 70 || !OUTCOME.test(t) || !shown(el)) continue;
head = t; headEl = el; root = el.parentElement;
}
if (root) {
var kids = root.querySelectorAll('p,span,div');
for (var j = 0; j < kids.length && !sub; j++) {
var k = kids[j];
if (ours(k) || k.children.length > 2 || !/(sub|text|summary|note|desc|detail)/.test(sig(k))) continue;
var tt = txt(k);
if (tt && tt !== head && tt.length >= 5 && tt.length <= 160 && shown(k)) sub = tt;
}
}
/* the result screen the button goes into: the nearest overlay / banner / result box around the headline */
var host = null;
for (var n = headEl, d = 0; n && n !== document.body && d < 4; n = n.parentElement, d++) {
if (d > 0 && BOX.test(sig(n)) && n.tagName !== 'BUTTON') { host = n; break; }
}
return { head: head, sub: sub, host: host };
}
var STATRE = /(score|moves|time|wpm|best|level|streak|accuracy|combo|coins|distance|height|points|stars|lives|wins|attempt|guess)/;
function readStats() {
var out = [], seen = {};
var all = document.body.querySelectorAll('span,strong,b,div,p,output');
for (var i = 0; i < all.length && out.length < 4; i++) {
var el = all[i];
if (ours(el) || el.children.length > 1) continue;
if (!STATRE.test(sig(el))) continue;
var t = txt(el);
if (!t || t.length > 28 || !/[0-9]/.test(t) || !shown(el)) continue;
if (!/[a-zA-Z]/.test(t) && el.parentElement) {
var parts = [], ch = el.parentElement.childNodes;
for (var p = 0; p < ch.length; p++) { var pv = (ch[p].textContent || '').replace(/\s+/g, ' ').trim(); if (pv) parts.push(pv); }
var pt = parts.join(' ');
if (pt.length <= 30 && /[a-zA-Z]/.test(pt)) t = pt;
}
var key = t.toLowerCase();
if (seen[key]) continue;
seen[key] = 1; out.push(t);
}
return out;
}
function bestCanvas() {
var cs = document.querySelectorAll('canvas'), best = null, area = 0;
for (var i = 0; i < cs.length; i++) {
var r = cs[i].getBoundingClientRect(), a = r.width * r.height;
if (a > area && a > 8000 && shown(cs[i])) { area = a; best = cs[i]; }
}
return best;
}
/* ---- show the button when a result is on screen ---- */
var lastHost = null, timer = 0;
function sync() {
timer = 0;
var r = readResult();
if (r.head && r.host) {
if (inl.parentElement !== r.host) r.host.appendChild(inl);
if (inl.hidden) inl.hidden = false;
if (!pill.hidden) pill.hidden = true;
} else {
if (!inl.hidden) inl.hidden = true;
if (pill.hidden) pill.hidden = false;
pill.classList.toggle('wdps-hot', !!r.head);
}
if (lastHost && !r.head && !box.hidden) box.hidden = true;
lastHost = r.head ? (r.host || document.body) : null;
}
function later() { if (!timer) timer = setTimeout(sync, 200); }
try {
new MutationObserver(function (list) {
for (var i = 0; i < list.length; i++) {
var t = list[i].target;
if (t.nodeType !== 1) t = t.parentElement;
if (t && !ours(t)) { later(); return; }
}
}).observe(document.body, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ['class', 'style', 'hidden'] });
} catch (e) {}
setInterval(later, 1500);
later();
/* ---- the card (1080 x 1080, drawn in memory, light like Pocket Artillery's) ---- */
var outline = 0;
function put(g, t, x, y) { if (outline) { g.lineJoin = 'round'; g.lineWidth = outline; g.strokeStyle = 'rgba(8,12,28,.85)'; g.strokeText(t, x, y); } g.fillText(t, x, y); }
function wrap(g, text, x, y, maxW, lh, maxLines) {
var words = text.split(' '), line = '', n = 0;
for (var i = 0; i < words.length; i++) {
var tst = line ? line + ' ' + words[i] : words[i];
if (g.measureText(tst).width > maxW && line) {
put(g, line, x, y); y += lh; n++; line = words[i];
if (n >= maxLines - 1) { line = words.slice(i).join(' '); break; }
} else line = tst;
}
if (line) {
while (line.length > 3 && g.measureText(line).width > maxW) line = line.slice(0, -2);
put(g, line, x, y); y += lh;
}
return y;
}
/* Biggest-screenshot card: the game frame fills the whole image, the text sits on top of it as an overlay. */
function bgOf(el) {
for (var n = el; n; n = n.parentElement) {
var c = getComputedStyle(n).backgroundColor;
if (c && c !== 'transparent' && c.slice(-4) !== ', 0)') return c;
}
return '#0f172a';
}
function drawBig(info, cv) {
var W = 1080, r = cv.width / cv.height, H = Math.max(810, Math.min(1350, Math.round(W / r)));
var c = document.createElement('canvas'); c.width = W; c.height = H;
var g = c.getContext('2d');
g.fillStyle = bgOf(cv.parentElement || cv); g.fillRect(0, 0, W, H);
var w = W, h = w / r;
if (h > H) { h = H; w = h * r; }
g.imageSmoothingEnabled = true; g.imageSmoothingQuality = 'high';
try { g.drawImage(cv, (W - w) / 2, (H - h) / 2, w, h); } catch (e) { return null; }
/* dark fades under the text so it stays readable on any game colours */
var g1 = g.createLinearGradient(0, 0, 0, H * 0.55); g1.addColorStop(0, 'rgba(8,12,28,.74)'); g1.addColorStop(1, 'rgba(8,12,28,0)');
g.fillStyle = g1; g.fillRect(0, 0, W, H * 0.55);
var g2 = g.createLinearGradient(0, H - 200, 0, H); g2.addColorStop(0, 'rgba(8,12,28,0)'); g2.addColorStop(1, 'rgba(8,12,28,.85)');
g.fillStyle = g2; g.fillRect(0, H - 200, W, 200);
var head = info.head || 'Can you beat me?';
var kind = /draw|tie/i.test(head) ? 'draw' : LOSS.test(head) && !WIN.test(head) ? 'loss' : 'win';
g.textAlign = 'center';
var y = 36;
g.fillStyle = 'rgba(255,255,255,.93)'; g.font = '800 34px system-ui, sans-serif'; outline = 7;
y = wrap(g, TITLE.toUpperCase(), W / 2, y + 34, 1000, 42, 1);
g.fillStyle = kind === 'draw' ? '#e2e8f0' : kind === 'loss' ? '#9db8ff' : '#ffc233';
var big = head.length > 22 ? 84 : 112; g.font = '900 ' + big + 'px system-ui, sans-serif'; outline = 16;
y = wrap(g, head, W / 2, y + big * 0.85, 1000, big * 1.05, 2);
if (info.sub) { g.fillStyle = '#fff'; g.font = '700 40px system-ui, sans-serif'; outline = 9; y = wrap(g, info.sub, W / 2, y + 6, 980, 50, 2); }
outline = 0;
if (info.stats.length) {
g.font = '800 38px system-ui, sans-serif';
var gap = 16, pad = 26, ws = [], tot = -gap;
for (var i = 0; i < info.stats.length; i++) { ws.push(g.measureText(info.stats[i]).width + pad * 2); tot += ws[i] + gap; }
var sc = tot > 960 ? 960 / tot : 1, px = (W - tot * sc) / 2, py = y + 14;
for (var k = 0; k < info.stats.length; k++) {
var w0 = ws[k] * sc;
g.fillStyle = 'rgba(8,12,28,.72)'; g.strokeStyle = 'rgba(255,255,255,.55)'; g.lineWidth = 3;
g.beginPath();
if (g.roundRect) g.roundRect(px, py, w0, 68, 34); else g.rect(px, py, w0, 68);
g.fill(); g.stroke();
g.fillStyle = '#fff'; g.font = '800 ' + Math.round(38 * sc) + 'px system-ui, sans-serif';
g.fillText(info.stats[k], px + w0 / 2, py + 47);
px += w0 + gap * sc;
}
}
outline = 8;
g.fillStyle = '#fff'; g.font = '900 52px system-ui, sans-serif'; put(g, 'Can you beat it?', W / 2, H - 84);
g.fillStyle = 'rgba(255,255,255,.92)'; g.font = '700 34px system-ui, sans-serif'; outline = 6; put(g, 'Play free at webdevpuneet.com', W / 2, H - 34);
outline = 0;
return c;
}
function finish(c, cb) {
var dataUrl = '';
try { dataUrl = c.toDataURL('image/png'); } catch (e) {}
try { c.toBlob(function (b) { cb(b, dataUrl); }, 'image/png'); } catch (e) { cb(null, dataUrl); }
}
function makeCard(info, cb) {
var cv0 = bestCanvas();
if (cv0) { var bc = drawBig(info, cv0); if (bc) { finish(bc, cb); return; } }
var S = 1080, c = document.createElement('canvas');
c.width = S; c.height = S;
var g = c.getContext('2d');
var gr = g.createLinearGradient(0, 0, 0, S);
gr.addColorStop(0, '#eaf4ff'); gr.addColorStop(1, '#fff3ef');
g.fillStyle = gr; g.fillRect(0, 0, S, S);
var cv = bestCanvas();
var head = info.head || 'Can you beat me?';
var kind = /draw|tie/i.test(head) ? 'draw' : LOSS.test(head) && !WIN.test(head) ? 'loss' : 'win';
g.textAlign = 'center';
g.fillStyle = '#1e293b'; g.font = '800 60px system-ui, sans-serif';
var y = wrap(g, TITLE, S / 2, cv ? 120 : 200, 980, 68, 1);
g.fillStyle = kind === 'draw' ? '#475569' : kind === 'loss' ? '#3b63e0' : '#e8553a';
g.font = '800 ' + (head.length > 22 ? 76 : 100) + 'px system-ui, sans-serif';
y = wrap(g, head, S / 2, y + (head.length > 22 ? 70 : 90), 980, head.length > 22 ? 84 : 108, 2);
if (info.sub) { g.fillStyle = '#475569'; g.font = '700 38px system-ui, sans-serif'; y = wrap(g, info.sub, S / 2, y + 4, 940, 48, 2); }
if (info.stats.length) {
g.font = '800 36px system-ui, sans-serif';
var gap = 18, pad = 26, ws = [], tot = -gap;
for (var i = 0; i < info.stats.length; i++) { ws.push(g.measureText(info.stats[i]).width + pad * 2); tot += ws[i] + gap; }
var sc = tot > 1000 ? 1000 / tot : 1, px = (S - tot * sc) / 2, py = y + 14;
for (var k = 0; k < info.stats.length; k++) {
var w0 = ws[k] * sc;
g.fillStyle = '#ffffff'; g.strokeStyle = '#d5e2ee'; g.lineWidth = 3;
g.beginPath();
if (g.roundRect) g.roundRect(px, py, w0, 64, 32); else g.rect(px, py, w0, 64);
g.fill(); g.stroke();
g.fillStyle = '#1e293b'; g.font = '800 ' + Math.round(36 * sc) + 'px system-ui, sans-serif';
g.fillText(info.stats[k], px + w0 / 2, py + 44);
px += w0 + gap * sc;
}
y = py + 64 + 10;
}
if (cv) {
try {
var maxW = 960, maxH = Math.max(180, 930 - y - 30), r = cv.width / cv.height;
var w = maxW, h = w / r;
if (h > maxH) { h = maxH; w = h * r; }
var x = (S - w) / 2, yy = y + 20 + Math.max(0, (maxH - h) / 2);
g.save(); g.shadowColor = 'rgba(60,100,140,0.3)'; g.shadowBlur = 30; g.shadowOffsetY = 10;
g.fillStyle = '#fff'; g.fillRect(x - 8, yy - 8, w + 16, h + 16); g.restore();
g.drawImage(cv, x, yy, w, h);
} catch (e) {}
}
g.fillStyle = '#1e293b'; g.font = '800 46px system-ui, sans-serif';
g.fillText('Can you beat it?', S / 2, 1000);
g.fillStyle = '#64748b'; g.font = '700 34px system-ui, sans-serif';
g.fillText('Play free at webdevpuneet.com', S / 2, 1050);
var dataUrl = '';
try { dataUrl = c.toDataURL('image/png'); } catch (e) {}
try { c.toBlob(function (b) { cb(b, dataUrl); }, 'image/png'); } catch (e) { cb(null, dataUrl); }
}
function shareText(info) {
var bits = [];
if (info.head) bits.push(info.head);
if (info.stats.length) bits.push(info.stats.join(', '));
return TITLE + ': ' + (bits.length ? bits.join(' - ') + '. ' : '') + 'Can you beat it? ' + URL;
}
function msg(t) { q('msg').textContent = t; }
function openFallback() {
var t = encodeURIComponent(shareText(lastInfo));
q('wa').href = 'https://wa.me/?text=' + t;
q('x').href = 'https://twitter.com/intent/tweet?text=' + t;
q('fb').href = 'https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(URL) + '"e=' + t;
box.hidden = false;
}
function nativeShare() {
/* a user cancel does nothing; anything else (blocked in an iframe, no permission) shows Copy / Download / links */
try {
navigator.share({ files: [file], title: TITLE, text: shareText(lastInfo) }).catch(function (e) { if (!e || e.name !== 'AbortError') openFallback(); });
} catch (e) { openFallback(); }
}
function onShare() {
var info = readResult(); info.stats = readStats();
lastInfo = info;
msg('Share your result:');
makeCard(info, function (b, dataUrl) {
blob = b; file = null;
if (b) { try { file = new File([b], 'result.png', { type: 'image/png' }); } catch (e) {} }
if (dataUrl) q('dl').href = dataUrl;
q('dl').hidden = !dataUrl;
var canNative = !!(file && navigator.share && navigator.canShare && navigator.canShare({ files: [file] }));
var touch = !!(window.matchMedia && window.matchMedia('(pointer: coarse)').matches);
q('more').hidden = !canNative;
if (canNative && touch) nativeShare();
else openFallback();
});
}
/* Games often have document/window level touch and pointer handlers (some call preventDefault, which cancels the tap's
click on phones, others restart the game on touchstart). So: keep every pointer event on our controls away from the
game, and fire on touchend as well as click (guarded so one tap shares once). */
var busy = 0;
function trigger() { if (busy) return; busy = 1; setTimeout(function () { busy = 0; }, 700); onShare(); }
function guard(el, act) {
var evs = ['pointerdown', 'pointerup', 'mousedown', 'mouseup', 'touchstart', 'touchend', 'click'];
for (var i = 0; i < evs.length; i++) el.addEventListener(evs[i], function (e) { e.stopPropagation(); });
if (act) {
el.addEventListener('touchend', function (e) { if (e.cancelable) e.preventDefault(); act(); });
el.addEventListener('click', function () { act(); });
}
}
guard(pill, trigger);
guard(inl, trigger);
guard(box);
q('more').addEventListener('click', function () { if (file) nativeShare(); });
q('close').addEventListener('click', function () { box.hidden = true; });
document.addEventListener('keydown', function (e) { if (e.key === 'Escape' && !box.hidden) box.hidden = true; });
q('copy').addEventListener('click', function () {
try {
navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]).then(
function () { msg('Image copied. Paste it into your chat or post.'); },
function () { msg('Could not copy here. Try Download image.'); }
);
} catch (e) { msg('Copying images is not supported here. Try Download image.'); }
});
})();
/* wdp-share:end */Extend with AI
Take This Snippet Further With AI
Paste this snippet into an AI assistant like Claude and ask it to extend the control set with align-self on individual balls, which introduces the idea that one item can opt out of the container's cross-axis alignment — the concept that trips up most people learning flexbox. Other good extensions: add flex-wrap levels where the stage is deliberately too narrow, add a par-moves target per level so players optimise rather than brute-force, add a "show me" button that animates the ghost solution's properties one at a time with the code panel narrating each change, or port the same ghost-layer-and-measure architecture to a CSS Grid version using grid-column, grid-row and place-items.
Prompt to recreate it
Copy this into your AI assistant of choice to build the effect from scratch, or as a jumping-off point for your own variant:
Build a playable flexbox alignment game in plain HTML, CSS, and JavaScript — no frameworks or libraries.
Requirements:
- A stage containing two absolutely positioned, identically sized layers: a non-interactive "ghost" layer of dashed target slots, and a live layer of coloured balls.
- A levels array where each level is a data object with a ball count, a plain-English goal, and a solution object of flex property values. Style the ghost layer with the solution object so the targets are positioned by real flexbox — never by hardcoded pixel coordinates.
- Control chips for flex-direction (row/column), justify-content (flex-start/center/flex-end/space-between) and align-items (flex-start/center/flex-end), applied to the live layer immediately on click, with the balls animating to their new positions.
- Detect a win positionally, not by comparing property values: measure both layers with getBoundingClientRect(), reduce each element to its centre point, and require every ball centre within a small pixel tolerance of a slot centre — so any property combination that genuinely lands the balls is accepted.
- Run the measurement inside requestAnimationFrame so it happens after the browser settles the new layout, and re-check on window resize.
- Print a live, copy-ready CSS declaration block showing display: flex plus the three currently selected values, updating on every change.
- Keep the three values in one state object and re-derive which chip is active from it, so the controls can never disagree with the applied styles. Count a move only when a click actually changes a value.
- Include at least six levels, several of which are only solvable in column mode so the player has to internalise the main-axis/cross-axis swap.Want to tighten it up first? Run this prompt through the AI Prompt Studio to score it across 8 quality dimensions, catch anti-patterns, and tune the wording for Claude, ChatGPT, or Gemini before you paste it in.