04Stacking order math — a painter's algorithm turning depth into z-index
Compute each block's z-index as the sum (col + row + height layer) ahead of time and the block behind is always drawn before the one in front. Drag a block to a new spot and the same formula reruns, so overlap sorts itself out.
Best forBuilder tools, diorama editors
z-indexCSS custom propertiescalc

<main class="stage">
<div class="ps" id="ps">
<p class="ps__hint">z-index = (col+row)×10 is recalculated every frame — as the traveling block crosses the grid, the front/back order flips on its own</p>
<div class="ps__field" role="img" aria-label="Scene where a moving block passes through fixed grid blocks and the depth order is recalculated">
<div class="ps__world" id="world"></div>
</div>
<p class="ps__meta">Traveler z-index = <b id="z">0</b></p>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
// 페인터 알고리즘 정렬(04) — 무대는 페이퍼. 고정 격자 블록은 z-index 를 한 번만 계산해
// 박아 두고, 이동 블록만 매 프레임 같은 공식((col+row)*10)을 다시 계산해 z-index 를
// 갱신한다 — 그래서 격자 사이를 지나가며 앞뒤가 저절로 뒤집힌다.
$duration: $dur-loop;
$easing: $ease-out;
$color: $subject-blue;
@include stage($stage-paper);
.ps {
display: flex; flex-direction: column; align-items: center; gap: $sp-2;
width: 100%; max-width: 420px;
}
.ps__hint {
margin: 0; font-weight: 700; font-size: clamp(10px, 2.6vw, 12px); line-height: 1.35;
color: $subject-ink; text-align: center;
}
.ps__field {
position: relative;
width: clamp(180px, 42vw, 220px); height: clamp(140px, 34vw, 168px);
display: grid; place-items: center;
}
.ps__world { position: relative; transform-style: preserve-3d; width: 1px; height: 1px; }
.ps__block {
position: absolute; left: 0; top: 0;
width: calc(var(--w) - 3px); height: calc(var(--w) - 3px);
transform: translate3d(var(--tx), var(--ty), 0) translate(-50%, -50%);
background: $subject-blue;
border: 1px solid rgba($subject-ink, .3);
border-radius: $r-xs;
box-shadow: $shadow-press;
}
.ps__block--traveler {
background: $subject-orange-deep;
box-shadow: $shadow-raised;
}
.ps__meta { margin: 0; font-size: clamp(9px, 2.4vw, 11px); color: rgba($subject-ink, .82); }
.ps__meta b { font-weight: 800; color: $subject-orange-deep; font-variant-numeric: tabular-nums; }
@media (max-width: 340px) {
.ps { gap: $sp-1; }
.ps__field { width: 156px; height: 112px; }
.ps__hint { font-size: 8px; }
.ps__meta { font-size: 7px; }
}
// reduce — 이동 블록이 안 돈다. 0.8 위상에 고정된 정지 장면만 남긴다.
@media (prefers-reduced-motion: reduce) {
.ps.is-still .ps__block { transition: none; }
}html, body {
margin: 0;
overflow: hidden;
}
.stage {
box-sizing: border-box;
min-height: 100vh;
display: grid;
place-items: center;
margin: 0;
background: #ffffff;
font-family: -apple-system, "Segoe UI", "Noto Sans KR", sans-serif;
padding: clamp(8px, 4vw, 24px);
}
.ps {
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
width: 100%;
max-width: 420px;
}
.ps__hint {
margin: 0;
font-weight: 700;
font-size: clamp(10px, 2.6vw, 12px);
line-height: 1.35;
color: #17141a;
text-align: center;
}
.ps__field {
position: relative;
width: clamp(180px, 42vw, 220px);
height: clamp(140px, 34vw, 168px);
display: grid;
place-items: center;
}
.ps__world {
position: relative;
transform-style: preserve-3d;
width: 1px;
height: 1px;
}
.ps__block {
position: absolute;
left: 0;
top: 0;
width: calc(var(--w) - 3px);
height: calc(var(--w) - 3px);
transform: translate3d(var(--tx), var(--ty), 0) translate(-50%, -50%);
background: #2f6df6;
border: 1px solid rgba(23, 20, 26, 0.3);
border-radius: 4px;
box-shadow: 0 6px 12px rgba(23, 20, 26, 0.32);
}
.ps__block--traveler {
background: #c93000;
box-shadow: 0 14px 24px rgba(23, 20, 26, 0.32);
}
.ps__meta {
margin: 0;
font-size: clamp(9px, 2.4vw, 11px);
color: rgba(23, 20, 26, 0.82);
}
.ps__meta b {
font-weight: 800;
color: #c93000;
font-variant-numeric: tabular-nums;
}
@media (max-width: 340px) {
.ps {
gap: 4px;
}
.ps__field {
width: 156px;
height: 112px;
}
.ps__hint {
font-size: 8px;
}
.ps__meta {
font-size: 7px;
}
}
@media (prefers-reduced-motion: reduce) {
.ps.is-still .ps__block {
transition: none;
}
}// 페인터 알고리즘 정렬(04) — 등각 장면에는 depth buffer 가 없다. 대신 "뒤에 있는 것부터
// 그린다"(화가의 순서)를 z-index 숫자로 흉내낸다. col+row 가 클수록 화면 앞쪽(카메라에
// 가깝다) 이므로 z-index 도 커야 한다. 이동 블록은 매 프레임 자신의 (col,row) 로 같은
// 공식을 다시 계산해 z-index 를 갱신한다 — 그래서 격자를 지나가면 앞뒤가 자동으로 뒤집힌다.
(function () {
var root = document.getElementById('ps');
var world = document.getElementById('world');
var zEl = document.getElementById('z');
if (!root || !world || !zEl) return;
function mat4RotateX(deg) {
var r = deg * Math.PI / 180, c = Math.cos(r), s = Math.sin(r);
return [1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1];
}
function mat4RotateZ(deg) {
var r = deg * Math.PI / 180, c = Math.cos(r), s = Math.sin(r);
return [c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
}
function mat4Mul(a, b) {
var out = new Array(16);
for (var col = 0; col < 4; col++) {
for (var row = 0; row < 4; row++) {
var sum = 0;
for (var k = 0; k < 4; k++) sum += a[k * 4 + row] * b[col * 4 + k];
out[col * 4 + row] = sum;
}
}
return out;
}
function mat4ToCss(m) {
var s = '';
for (var i = 0; i < m.length; i++) s += (i ? ',' : '') + m[i].toFixed(6);
return 'matrix3d(' + s + ')';
}
var TILT = -35.264;
world.style.transform = mat4ToCss(mat4Mul(mat4RotateX(TILT), mat4RotateZ(45)));
var mm = window.matchMedia('(max-width: 340px)').matches;
var N = 4;
var TILE_W = mm ? 30 : 38, TILE_H = mm ? 15 : 19;
var SIDE = mm ? 26 : 34;
function place(el, col, row) {
var x = (col - row) * TILE_W / 2;
var y = (col + row) * TILE_H / 2;
el.style.setProperty('--tx', x.toFixed(2) + 'px');
el.style.setProperty('--ty', y.toFixed(2) + 'px');
}
// 고정 격자 블록 — z-index 는 한 번만 계산해서 고정
for (var row = 0; row < N; row++) {
for (var col = 0; col < N; col++) {
var block = document.createElement('div');
block.className = 'ps__block';
block.style.setProperty('--w', SIDE + 'px');
place(block, col, row);
block.style.zIndex = String(Math.round((col + row) * 10));
world.appendChild(block);
}
}
// 이동 블록 — 매 프레임 (col,row) 를 다시 계산해 같은 공식으로 z-index 를 갱신한다
var traveler = document.createElement('div');
traveler.className = 'ps__block ps__block--traveler';
traveler.style.setProperty('--w', SIDE + 'px');
world.appendChild(traveler);
var CENTER = (N - 1) / 2;
var RADIUS = CENTER + 0.35;
function paint(t) {
var ang = t * 0.9;
var col = CENTER + Math.cos(ang) * RADIUS;
var row = CENTER + Math.sin(ang) * RADIUS;
place(traveler, col, row);
var z = Math.round((col + row) * 10) + 1; // +1 — 같은 칸일 때 이동 블록이 위로
traveler.style.zIndex = String(z);
zEl.textContent = String(z);
}
var reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
if (reduce) {
paint(0.8);
root.classList.add('is-still');
} else {
var start = performance.now();
(function step(now) {
paint((now - start) / 1000);
requestAnimationFrame(step);
})(start);
}
})();// IsometricPainterStackingOrder — vanilla 판(run/333/demo/04-isometric-painter-stacking-order/index.html)
// 의 React 포트. 고정 블록은 z-index = round((col+row)*10) 을 한 번만 계산해 굳히고,
// 궤도를 도는 이동 블록만 매 프레임 같은 공식으로 z-index 를 다시 계산해 앞뒤를 뒤집는다.
import { useEffect, useRef } from "react";
import styles from "./IsometricPainterStackingOrder.module.scss";
export type IsometricPainterStackingOrderProps = {
duration?: string;
easing?: string;
color?: string;
};
type Box<T> = { current: T };
const HINT = "z-index = (col+row)×10 을 매 프레임 계산해 대입합니다 — 이동 블록이 격자를 가로지르며 앞뒤가 저절로 뒤집힙니다";
const ARIA_FIELD = "이동하는 블록이 고정 격자 블록들 사이를 지나며 앞뒤 순서가 계산으로 바뀌는 장면";
const LABEL_Z = "이동 블록 z-index = ";
const N = 4;
const TILE_W = 40, TILE_H = 20;
const CENTER = (N - 1) / 2;
const RADIUS = CENTER + 0.35;
function toScreen(col: number, row: number): { x: number; y: number } {
return { x: ((col - row) * TILE_W) / 2, y: ((col + row) * TILE_H) / 2 };
}
export default function IsometricPainterStackingOrder({
duration = "2s",
easing = "linear",
color = "#c93000"
}: IsometricPainterStackingOrderProps) {
const rootRef = useRef<HTMLDivElement | null>(null);
const worldRef = useRef<HTMLDivElement | null>(null);
const travelerRef = useRef<HTMLDivElement | null>(null);
const zTextRef = useRef<HTMLElement | null>(null);
const rafRef = useRef(0) as Box<number>;
useEffect(() => {
const world = worldRef.current;
const traveler = travelerRef.current;
const root = rootRef.current;
if (!world || !traveler || !root) return;
let minX = Infinity, maxX = -Infinity, maxY = -Infinity;
const blocks: { x: number; y: number }[] = [];
for (let row = 0; row < N; row++) {
for (let col = 0; col < N; col++) {
const p = toScreen(col, row);
if (p.x < minX) minX = p.x;
if (p.x > maxX) maxX = p.x;
if (p.y > maxY) maxY = p.y;
blocks.push(p);
}
}
const shiftX = -(minX + maxX) / 2;
const shiftY = -maxY / 2;
let idx = 0;
for (let row = 0; row < N; row++) {
for (let col = 0; col < N; col++) {
const p = blocks[idx++];
const el = document.createElement("div");
el.className = styles.block;
el.style.setProperty("--tx", (p.x + shiftX).toFixed(2) + "px");
el.style.setProperty("--ty", (p.y + shiftY).toFixed(2) + "px");
el.style.zIndex = String(Math.round((col + row) * 10));
world.appendChild(el);
}
}
world.appendChild(traveler);
function paint(t: number): void {
const ang = t * 0.9;
const col = CENTER + Math.cos(ang) * RADIUS;
const row = CENTER + Math.sin(ang) * RADIUS;
const p = toScreen(col, row);
traveler!.style.setProperty("--tx", (p.x + shiftX).toFixed(2) + "px");
traveler!.style.setProperty("--ty", (p.y + shiftY).toFixed(2) + "px");
const z = Math.round((col + row) * 10) + 1;
traveler!.style.zIndex = String(z);
if (zTextRef.current) zTextRef.current.textContent = String(z);
}
const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
if (reduce) {
paint(0.7);
root.classList.add(styles.isStill);
} else {
const start = performance.now();
const step = (now: number): void => {
paint((now - start) / 1000);
rafRef.current = requestAnimationFrame(step);
};
rafRef.current = requestAnimationFrame(step);
}
return () => {
cancelAnimationFrame(rafRef.current);
while (world.firstChild) world.removeChild(world.firstChild);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<main className={styles.stage}>
<div className={styles.ps} ref={rootRef} data-duration={duration} data-easing={easing} data-color={color}>
<p className={styles.hint}>{HINT}</p>
<div className={styles.field} role="img" aria-label={ARIA_FIELD}>
<div className={styles.world} ref={worldRef}>
<div className={styles.blockTraveler} ref={travelerRef}></div>
</div>
</div>
<p className={styles.meta}>
<span className={styles.metaLabel}>{LABEL_Z}</span>
<b className={styles.zVal} ref={zTextRef}>0</b>
</p>
</div>
</main>
);
}04 Stacking order math — a painter's algorithm turning depth into z-index — Measured area 4.119% · moving frames 23/23Original by GODRICH · SCSS and React ship in the zip · Isometric CSS: 9 True-Projection 3D Dioramas
The post this demo lives in
Isometric CSS: 9 True-Projection 3D DioramasIsometric css done right: Each cube face shades by a light-angle calc, grid coords map to screen via the 2:1 isometric f See all demos in this post
If you like this effect - similar demos
Interactions07 A Two-Layer Crackle Where Grains Split Into Smaller Bursts at the End of Their LifeCSS Fireworks: 9 Bursts, Trails and Reflections
Interactions02 Card stack that shifts by depth3D Hover Effect CSS: 9 Pointer-Following Scenes
Interactions07 Order number boardKiosk UI Design: 9 Finger-Sized Order Screens