Responsive scene
An illustration that recomposes itself as its container narrows, using viewBox and container queries.
What you are seeing
A white frame holds a small illustration of a house with a blue roof, under a yellow sun on a pale blue sky. In a wide frame there are also far hills, clouds, birds, smoke, a second house and trees. A magenta handle on the right edge resizes the frame, and a label gives its width in pixels.
How it works
Media queries look at the window, but an embedded illustration needs to react to the space it is given. A container query does that. The frame here is marked as a size container, and CSS rules inside it hide far details and move the sun as the frame narrows.
CSS cannot change a viewBox, so a ResizeObserver chooses between three crops of the same drawing based on the frame shape. Narrow frames crop in tightly around the house, so the main subject stays large.
Together, the crop and the container rules give three compositions from one SVG: wide, medium and narrow.
Source
/lab/responsive-scene/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Responsive scene</title>
<meta name="description" content="An illustration that recomposes itself as its container narrows, using viewBox and CSS container queries.">
<link rel="stylesheet" href="../lab.css">
<style>
.stage{display:flex;justify-content:center;align-items:stretch;padding:10px 0}
.frame{container-type:inline-size;position:relative;height:100%;width:90%;max-width:100%;background:#fff;border:1px solid var(--line)}
.frame>svg{position:absolute;left:0;top:0;width:100%;height:100%;display:block;overflow:hidden}
.grip{position:absolute;right:-10px;top:50%;width:20px;height:64px;margin-top:-32px;border-radius:10px;background:var(--mag);border:2px solid #fff;cursor:ew-resize;touch-action:none;z-index:2}
.grip::after{content:"";position:absolute;left:5px;right:5px;top:22px;height:16px;border-left:2px solid #fff;border-right:2px solid #fff}
.tag{position:absolute;left:6px;top:6px;font-size:11px;background:#24272c;color:#fff;border-radius:4px;padding:1px 6px;z-index:1}
.sun{transition:transform .25s}
@container (max-width:359px){.far{display:none}.sun{transform:translate(-120px,10px)}}
@container (max-width:219px){.mid{display:none}.sun{transform:translate(-150px,14px)}}
</style>
</head>
<body>
<main class="demo">
<div class="stage" id="stage">
<div class="frame" id="frame">
<span class="tag" id="tag"></span>
<svg id="svg" viewBox="0 0 400 300" role="img" aria-labelledby="t d" preserveAspectRatio="xMidYMid slice">
<title id="t">Responsive scene</title>
<desc id="d">A small house with a blue roof under a yellow sun. In a wide container the scene also shows far hills, clouds, birds, smoke, a second house and trees. As the container narrows the extra details disappear and the view crops in around the house.</desc>
<rect x="-200" y="-200" width="800" height="700" fill="#d6e0ff"/>
<g class="far">
<path d="M-200 220 Q-60 120 80 215 T330 205 T600 215 V300 H-200Z" fill="#b2c4f0"/>
<g fill="#fff"><ellipse cx="90" cy="60" rx="34" ry="12"/><ellipse cx="116" cy="52" rx="22" ry="12"/><ellipse cx="340" cy="130" rx="30" ry="10"/></g>
<g fill="none" stroke="#24272c" stroke-width="2" stroke-linecap="round"><path d="M150 40 q6 -8 12 0 q6 -8 12 0"/><path d="M190 62 q5 -7 10 0 q5 -7 10 0"/></g>
<g fill="#c6cbd6"><circle cx="228" cy="95" r="9"/><circle cx="238" cy="78" r="12"/></g>
</g>
<rect x="-200" y="215" width="800" height="200" fill="#a9cf9a"/>
<g class="sun"><circle cx="320" cy="62" r="26" fill="#ffc933"/></g>
<g class="mid">
<g transform="translate(18 0)"><rect x="40" y="170" width="56" height="50" fill="#fff" stroke="#24272c" stroke-width="2"/><polygon points="34,170 68,140 102,170" fill="#24272c"/></g>
<g transform="translate(290 0)"><rect x="12" y="170" width="8" height="50" fill="#6b4a2b"/><circle cx="16" cy="158" r="26" fill="#3d9a5a"/></g>
<g transform="translate(335 18)"><rect x="12" y="170" width="8" height="32" fill="#6b4a2b"/><circle cx="16" cy="162" r="18" fill="#2f8a50"/></g>
</g>
<g class="house">
<rect x="160" y="146" width="80" height="74" fill="#fff" stroke="#24272c" stroke-width="3"/>
<polygon points="148,148 200,102 252,148" fill="#1f3fe0" stroke="#24272c" stroke-width="3" stroke-linejoin="round"/>
<rect x="190" y="180" width="20" height="40" fill="#24272c"/>
<rect x="167" y="160" width="16" height="16" fill="#d6e0ff" stroke="#24272c" stroke-width="2"/><rect x="217" y="160" width="16" height="16" fill="#d6e0ff" stroke="#24272c" stroke-width="2"/>
<rect class="far" x="222" y="108" width="12" height="26" fill="#24272c"/>
</g>
</svg>
<div class="grip" id="grip" role="slider" tabindex="0" aria-label="Container width" aria-valuemin="120" aria-valuemax="400" aria-valuenow="300"></div>
</div>
</div>
<div class="bar">
<button id="auto" type="button">Pause</button>
<label><span>Container width</span><input id="w" type="range" min="120" max="600" value="400"></label>
<output id="out"></output>
</div>
</main>
<script src="../lab.js"></script>
<script src="demo.js"></script>
</body>
</html>
/lab/responsive-scene/demo.js
(function () {
'use strict';
var $ = Lab.$, frame = $('#frame'), svg = $('#svg'), stage = $('#stage'), grip = $('#grip'), range = $('#w'), width = 300, auto = false, t = 0;
function maxW() { return Math.max(160, stage.clientWidth - 28); }
function setW(w) {
width = Lab.clamp(Math.round(w), 120, maxW());
frame.style.width = width + 'px';
range.max = maxW(); range.value = width;
grip.setAttribute('aria-valuenow', width); grip.setAttribute('aria-valuemax', maxW());
}
function compose() {
var w = frame.clientWidth, h = frame.clientHeight, ar = w / h, vb, name;
if (w < 220) name = 'narrow'; else if (w < 360) name = 'medium'; else name = 'wide';
// The viewBox crops in as the frame gets narrower, so the house stays large.
if (ar > 1.2) vb = '0 0 400 300'; else if (ar > 0.8) vb = '70 30 260 270'; else vb = '115 60 170 200';
svg.setAttribute('viewBox', vb);
$('#tag').textContent = w + 'px';
$('#out').textContent = name + ' layout, viewBox ' + vb;
}
new ResizeObserver(compose).observe(frame);
var loop = Lab.loop(function (dt) { t += dt * 0.5; setW(160 + (Math.sin(t) * 0.5 + 0.5) * (maxW() - 160)); });
function setAuto(on) { auto = on; $('#auto').textContent = on ? 'Pause' : 'Auto resize'; if (on) loop.start(); else loop.stop(); }
$('#auto').addEventListener('click', function () { setAuto(!auto); });
range.addEventListener('input', function () { setAuto(false); setW(+range.value); });
// The grip is HTML, so it uses client coordinates. The frame is centred, so width is twice the distance from the centre.
var dragging = false;
grip.addEventListener('pointerdown', function (e) { dragging = true; setAuto(false); grip.setPointerCapture(e.pointerId); e.preventDefault(); });
grip.addEventListener('pointermove', function (e) { if (!dragging) return; var r = stage.getBoundingClientRect(); setW(2 * Math.abs(e.clientX - (r.left + r.width / 2))); });
grip.addEventListener('pointerup', function () { dragging = false; });
grip.addEventListener('pointercancel', function () { dragging = false; });
grip.addEventListener('keydown', function (e) {
var s = e.shiftKey ? 40 : 10;
if (e.key === 'ArrowRight' || e.key === 'ArrowUp') setW(width + s); else if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') setW(width - s);
else if (e.key === 'Home') setW(120); else if (e.key === 'End') setW(maxW()); else return;
setAuto(false); e.preventDefault();
});
window.addEventListener('resize', function () { setW(width); });
setW(Math.min(420, maxW())); compose();
if (Lab.reduced) setAuto(false); else setAuto(true);
})();
/lab/lab.js
/* Small shared helpers for the SVG Wow! lab demos. No dependencies. */
(function () {
'use strict';
var NS = 'http://www.w3.org/2000/svg';
var mq = window.matchMedia('(prefers-reduced-motion: reduce)');
var Lab = (window.Lab = { NS: NS });
Object.defineProperty(Lab, 'reduced', { get: function () { return mq.matches; } });
Lab.$ = function (s, r) { return (r || document).querySelector(s); };
Lab.$$ = function (s, r) { return Array.prototype.slice.call((r || document).querySelectorAll(s)); };
Lab.clamp = function (v, a, b) { return Math.max(a, Math.min(b, v)); };
Lab.lerp = function (a, b, t) { return a + (b - a) * t; };
Lab.ease = function (t) { return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2; };
Lab.make = function (tag, attrs, parent) {
var e = document.createElementNS(NS, tag);
if (attrs) for (var k in attrs) e.setAttribute(k, attrs[k]);
if (parent) parent.appendChild(e);
return e;
};
/* Client point to the user space of `el` (any SVG graphics element). */
Lab.pt = function (el, evt) {
var m = el.getScreenCTM();
if (!m) return { x: 0, y: 0 };
var p = new DOMPoint(evt.clientX, evt.clientY).matrixTransform(m.inverse());
return { x: p.x, y: p.y };
};
/* requestAnimationFrame loop that pauses while the document is hidden. */
Lab.loop = function (fn) {
var raf = 0, last = 0, running = false, wanted = false, self = {};
function tick(t) {
if (!running) return;
raf = requestAnimationFrame(tick);
var dt = last ? Math.min((t - last) / 1000, 0.1) : 0;
last = t;
fn(dt, t / 1000);
}
function go() { if (running || document.hidden || !wanted) return; running = true; last = 0; raf = requestAnimationFrame(tick); }
function halt() { running = false; cancelAnimationFrame(raf); }
self.start = function () { wanted = true; go(); };
self.stop = function () { wanted = false; halt(); };
self.running = function () { return wanted; };
document.addEventListener('visibilitychange', function () { if (document.hidden) halt(); else go(); });
return self;
};
/* Pointer drag with capture. space: element whose user space the points use. */
Lab.drag = function (el, o) {
var active = false, space = o.space || el.ownerSVGElement || el;
el.addEventListener('pointerdown', function (e) {
if (e.button > 0) return;
active = true;
try { el.setPointerCapture(e.pointerId); } catch (_) {}
if (o.down) o.down(Lab.pt(space, e), e);
e.preventDefault();
});
el.addEventListener('pointermove', function (e) { if (active) o.move(Lab.pt(space, e), e); });
function end(e) {
if (!active) return;
active = false;
try { el.releasePointerCapture(e.pointerId); } catch (_) {}
if (o.up) o.up(e);
}
el.addEventListener('pointerup', end);
el.addEventListener('pointercancel', end);
};
Lab.say = function (msg) {
var l = document.getElementById('live');
if (l) l.textContent = msg;
};
})();
/lab/lab.css
:root{--bg:#f1f2f4;--ink:#24272c;--blue:#1f3fe0;--mag:#d4006a;--line:#c9ccd3;--panel:#fff;--muted:#555b66;font-family:system-ui,-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif}
*{box-sizing:border-box}
html,body{margin:0;height:100%;background:var(--bg);color:var(--ink);overflow-x:hidden}
body{font-size:13px;line-height:1.3}
.demo{display:flex;flex-direction:column;height:100%;min-height:0}
.stage{flex:1 1 auto;min-height:120px;position:relative;overflow:hidden;background:var(--bg)}
.stage>svg{position:absolute;left:0;top:0;width:100%;height:100%;display:block}
.bar{flex:0 0 auto;display:flex;flex-wrap:wrap;gap:6px 14px;align-items:center;padding:6px 10px;background:var(--panel);border-top:1px solid var(--line);max-height:46%;overflow:auto}
.bar .grp{display:flex;flex-wrap:wrap;align-items:center;gap:6px 10px}
label{display:inline-flex;align-items:center;gap:6px;white-space:nowrap}
label>span,.dim{color:var(--muted)}
output{font-variant-numeric:tabular-nums;min-width:3.2ch;display:inline-block}
button,select,input[type=number],input[type=text]{font:inherit;color:var(--ink);background:#fff;border:1px solid #8a909b;border-radius:6px;padding:3px 8px;min-height:28px}
button{border-color:var(--ink);cursor:pointer}
button:hover{background:#e7e9ef}
button[aria-pressed=true]{background:var(--ink);color:#fff}
input[type=range]{width:110px;accent-color:var(--blue);margin:0}
input[type=color]{width:34px;height:28px;padding:1px;border:1px solid #8a909b;border-radius:6px;background:#fff}
input[type=checkbox]{accent-color:var(--blue);width:16px;height:16px}
:focus-visible{outline:3px solid var(--blue);outline-offset:2px}
.grab{cursor:grab;touch-action:none}
.grab:active{cursor:grabbing}
.grab:focus-visible{outline:none;stroke:var(--blue);stroke-width:4px}
.drag-surface{touch-action:none}
.ro{font-size:11px;color:var(--muted)}
.sr-only{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
svg text{font-family:inherit}
pre,textarea{font:11px/1.35 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
@media (pointer:coarse){button,select,input[type=number]{min-height:38px}input[type=range]{height:30px}}
@media (max-width:420px){.bar{gap:6px 10px;padding:6px 8px}input[type=range]{width:96px}}
@media (min-width:700px){.demo.split{flex-direction:row}.demo.split .stage{flex:1 1 auto}.demo.split .bar{width:320px;max-height:none;flex:0 0 320px;border-top:0;border-left:1px solid var(--line);align-content:flex-start}}