---
name: mockup-to-html
description: Turn a design mockup (PNG/JPG of a page or hero) into HTML and CSS that matches it, by measuring the mockup instead of eyeballing it. Use when asked to build a page from a mockup, match a design in code, or reproduce a screenshot as markup.
allowed-tools: Bash, Read, Write, Edit
---

# Mockup to HTML

Rebuilding a mockup is a measurement problem, not a taste problem. Every choice
below follows one rule: **read the value off the mockup, don't guess it, and
verify it with a diff.** When something looks off you go back and measure again;
you never nudge numbers until it looks right, because that trades a bug you can
find for a bug you cannot.

**First, look for the design's own plate.** Nothing in this workflow pays off faster
than finding that the mockup shipped with its background separated out. Design
pipelines routinely export one — a `plate-*.jpg` next to the comp, a layer folder,
a `background.png`. If it exists, use it as the asset: it is exact, free, instant,
and it removes the need to crop, inpaint or generate anything. In a nine-design
batch it turned four full-bleed photo heroes and two panel layouts into ~3 cycles
each, because the photography, the panel split and the bottom bar were all already
there. Check before you measure anything else; the search costs one `ls`.

Expect roughly 10 to 15 render/measure cycles. Each one should be driven by a
number, not a hunch. Measured on three unrelated 1536x864 designs: 12 cycles to MAE
18.2 on a dark map hero, 9 cycles to 13.4 on a serif-and-card hero, 9 cycles to 16.9
on a dark schematic hero with monospace data and a 200px numeral. The
measure→diff→correct loop did not change between them; what did *not* transfer was
the landmark region set, the assumption of a single typeface, and the colour model
(one design is near-white ink on dark, another mixes a light card into the same
frame).

## Ground rules

- **The mockup's own pixel grid is the reference.** Do not trust a stated design
  width; open the file and use its real dimensions. If it is 1536x864, the design
  grid is 1536x864 and heights follow from the aspect ratio.
- **Never hard-code heights.** Content flows; the hero gets `min-height` and
  padding, and the numbers fall out of the padding.
- **Never bake text into a generated image.** Any string visible in a raster
  asset is rebuilt as HTML — the image model would garble it and you could never
  edit it again.
- **Never recreate rich imagery in HTML/SVG.** Maps, photos, illustrations, and
  textured plates come from an image model. Simple pictograms (a circle, a tree,
  a building silhouette at 30px) are fair game as inline SVG.
- **Opinions are not evidence.** If you cannot point at a measurement, you do not
  know it.

## Layout of a project using this skill

```
mock.jpg            the design to match
src/index.html      the page
src/styles.css      the stylesheet
src/assets/         generated raster assets
shots/              one render per iteration, plus comparisons
tools/              copied from this skill's tools/
```

Copy `tools/` into the project. All tools resolve paths relative to the project
root (the parent of `tools/`) and can be pointed elsewhere with flags.

## Step 1 — Read the mockup

Do this before writing any markup. Ten minutes here saves ten iterations later.

```bash
python3 tools/measure.py --region 0,0,1536,120 --thresh 150 --color
python3 tools/measure.py --region 0,150,1400,540 --thresh 190 --rows --min-gap 6
```

`measure.py` reports ink bounding boxes for bright-on-dark (or dark-on-light with
`--invert`) content, plus mean/p95 ink colour and the local background. Use it to
pull out:

- **The palette.** Sample the ink colour at its 99th percentile (not the mean —
  antialiasing drags the mean toward the background), and the plate colour at the
  median of the non-ink pixels.
- **Gutters.** The ink's left edge is *not* the container edge; a glyph has a left
  side bearing. Solve for the container by measuring several elements: if the
  eyebrow, subhead, stats and button all sit at ink x=43 and the headline's `D`
  sits at 58, the container is ~42 and the headline has an extra inset. Large type
  is often optically inset — expect the header gutter and the hero gutter to
  differ, and expect them both to differ from the ink.
- **Baselines.** Split a column into rows to get exact baselines and line pitch.
  Line pitch (baseline to baseline) is what `line-height` must reproduce.
- **Cap heights and x-heights.** Measure a flat-topped capital (`H`, `M`, `E`) for
  cap height and a flat lowercase letter (`x`, `u`, `n`) for x-height. Round
  letters like `O` and `D` overshoot by a pixel or two on each side.

Write the numbers down. They seed the stylesheet directly.

## Step 2 — Build the plate reference, then generate assets

**Pass the mockup itself as a reference.** `tools/genimg.py --ref mock.jpg` sends
it through `input_references`, which is how the model is meant to see a design.
With a reference the model reproduces the mockup's actual composition — street
grid orientation, camera, layout — which a text prompt alone will not. Use text
only for what the reference cannot carry: the palette you want, and the list of
things to remove.

Ask for **one component at a time**, and crop the reference to the region you want
back when the component is small. Upscale that crop 4-6x first so the model can
see the detail it is being asked to redraw. `--background transparent` returns an
asset you can drop straight into the page.

Prefer `--aspect`/`--resolution` over `--size`, so you get the mockup's aspect
directly instead of generating at the nearest supported aspect and cropping. The
provider only accepts a fixed set, and it will tell you which when you get it
wrong:

```
400 No provider for ... supports the requested parameter(s): aspect_ratio "1:4".
    Provider rejections: OpenAI: aspect_ratio: not supported.
    Accepted: 1:1, 3:2, 2:3, 4:3, 3:4, 16:9, 9:16, 21:9, auto, 4:5, 5:4, 2:1, ...
```

Pick the closest accepted ratio to the component's own ink box and let it sit in a
transparent frame; do not fight it.

This is cheap enough to do per component. In practice: a 1.5K 16:9 plate cost
$0.044 and a 1K transparent icon cost $0.022, against $0.17 for a larger
text-only generation. Recovering a design's one genuinely rich illustration this
way beat an inline-SVG approximation of it on both fidelity and effort, and
reference-guided generation of the background plate cut whole-image MAE from 23.1
to 18.5 in one call — by far the largest single improvement in that build.

**Then re-check the scrim, and expect to delete it.** A scrim is what you reach for
while the plate is still a stranger's photograph under your text. Once the plate is
generated from the mockup and tone-matched to it, the scrim is double-darkening, and
it will be the largest remaining error that has nothing to do with type. Sweep it
like anything else instead of leaving it in by reflex:

```bash
for A in 0.00 0.12 0.30 0.50; do   # patch the gradient stop, re-render, compare
```

In that build MAE fell monotonically as the scrim went to zero, and the final answer
was no desktop scrim at all -- only the mobile override, which exists because
cover-fitting a 16:9 plate into a portrait frame makes the falloff meaningless.

Inline SVG is still the right answer for simple pictograms (a ring, a tree, a
triangle): they scale, they inherit `currentColor`, and they cost nothing. Reach
for the model when the component has real internal detail.

You cannot see what is behind the type in a mockup, and you cannot tone-match a
generated asset to something you cannot see. Recover it first:

```bash
python3 tools/inpaint.py --img mock.jpg --out work/plate.png --thresh 118
```

This masks everything brighter than the plate and grows the known region inwards
until the holes are filled. The result shows the background's actual structure and
its real tone distribution. Use it for two things: writing a better generation
prompt, and as the tone target.

Inventory the raster assets before generating anything. For each one, write a
prompt that specifies:

- **Medium and subject** ("flat top-down vector street map of a dense city
  centre").
- **An exact duotone and explicit colour bans** ("deep teal-green; no blue, no
  yellow, no red, no white").
- **Structure and scale in pixels** — from the recovered plate you can often say
  how many pixels apart the lines are. Be concrete; vague prompts produce vague
  texture.
- **A hard list of exclusions**, including text: "no text, no labels, no icons,
  no pins, no compass, no attribution, no vignette, no gradient."

```bash
export OPENROUTER_API_KEY=...
python3 tools/genimg.py --prompt-file work/prompt-map.txt \
    --size 1536x1024 --out work/bg-gen.png
```

Image models generally do not honour 16:9. Generate at the nearest supported
aspect (e.g. 1536x1024) and cover-fit: the tool crops to the target box.

Then **tone-match** onto the recovered plate rather than stacking CSS filters:

```bash
python3 tools/matchplate.py --src work/bg-gen.png --ref work/plate.png \
    --width 1536 --height 864 --out src/assets/map.png
```

This remaps the asset by *rank*: each pixel takes the colour the plate has at the
same percentile, which transfers tone, contrast and hue in one step and keeps the
asset's own structure. It prints both luminance distributions so you can confirm
the match. Because the plate already contains the design's light falloff, the CSS
scrim afterwards can be nearly nothing — a `.30` black-to-transparent wash where
the copy sits, not a heavy gradient.

If the hue is right but the contrast is off, `--gain 0.85` flattens it about its
mean. `tools/tone.py` is the simpler alternative when you have an explicit
two-stop ramp to hand.

Run the same normalisation for a **monospace** face when the design uses one; the
tool does not care that the family is mono, and a data-readout design will have two
type systems rather than one. JetBrains Mono came out at +0px and -0.002em on a real
readout against seven alternatives, which is the same decisive signal a display serif
gives.

### The plate must not eat the subject

Asking a model to "remove all text" is the obvious instruction and it is wrong.
It removes the hero's headline — which is the point — and it also removes the
print on a coffee bag, the signage on a building, the title on a book. Those are
*the subject*. The built page cannot put them back, so the plate stops being the
same photograph, and the page is permanently wrong wherever the artwork carries
in-scene lettering. Measured on two comps: a product label and a building sign
were both erased, leaving a blank kraft bag and a blank concrete facade.

The distinction to encode is **overlay type vs in-scene text**:

- *Overlay type* is what the page's own layout produced — headline, subhead,
  eyebrow, navigation, buttons, badges, captions. It floats over the artwork as
  flat composition: crisp, evenly set, on a panel or a colour field or the sky.
  **Remove it.**
- *In-scene text* is printed, painted, mounted or engraved on a surface inside the
  photograph — packaging, product labels, signage, fascias, book spines, wall
  posters, gallery labels, clothing prints, vehicle livery. **Keep it.**

**Mask the type, and be explicit about the small print.** Even with the
instruction fixed, a full-frame decomposition re-renders everything: in one test
the flat background came back five levels lighter ((19,19,17) → (24,23,21)), and
flat areas are most of a hero, so that drift costs more than recovering the
signage gains. A mask over the type fixes the drift — everything outside it is
preserved by construction, so in-scene text cannot be touched.

But a mask does **not** remove the type on its own. Given a mask over all of the
page's text, the model erased the 300px headline and left **30%** of the small
glyphs — the logo, the nav items, the eyebrow, the bottom strip. Those sat under
the HTML text as a ghost, offset by a few pixels, which reads as doubled text.
Two things were wrong:

- **The prompt has to name the small text.** "Fill the masked area with the
  surrounding background" gets you the headline and nothing else. Say it
  explicitly: *erase every glyph inside the masked area — the headline, the
  eyebrow, the navigation items, the logo lettering, the buttons, the body copy
  and the small print along the bottom — including the small ones.*
- **The art region must cover the artwork's whole extent.** Excluding only
  `y95–750` left the building's top and bottom corners inside the mask, so the
  model repainted parts of the subject while being told not to.

**Verify by residual ink, never by MAE.** This is the trap that made the whole
mistake invisible for several rounds: a plate that *keeps* the type matches the
comp more closely than one that removes it, so the score **improves** while the
plate is wrong and the page shows doubled text. Measured on the same build,
13.26 for the doubled-text plate against 16.32 for the clean one. The MAE cannot
see this, and will actively reward it — the same failure mode as judging weight
by MAE. The check is:

```
python3 tools/plate.py --comp mock.jpg --art-region 884,0,1536,864 --out plate.jpg --prompt "..."
  residual type inside mask: 0/75694 px = 0.0%
```

`plate.py` reports it and warns above 15%. Anything above zero means glyphs are
still in the plate; the built page will show them under the real text.

Results on the two failing comps, all plates verified at 0% residual:

| comp | no plate fix | fixed plate |
|---|---|---|
| coffee bag — label and wordmark restored | 18.15 | **16.10** |
| building — signage restored | 15.73 | **16.32** |

Note the second one scores *worse* than the plate that erased the building's
sign. That plate was wrong: it destroyed the subject to buy 0.6 of MAE. Correct
and slightly worse beats very slightly better and wrong.

## Step 3 — Identify the typefaces

Never pick a font by eye, and never trust font-size. Families have different
x-height ratios, so the same font-size looks like different sizes. Normalise by
**x-height** and let the residual width be the thing you measure.

```bash
python3 tools/fontspec.py --text "Deliver vetted restaurants," \
    --mock-line 30,195,1400,300 --xh 60 --fonts "Inter:900,Roboto:900,Archivo:900" \
    --sheet work/specimen.png --overlay work/ov
```

The table gives, per candidate, the font-size that reproduces the mockup's
x-height, the resulting ink width, and the `letter-spacing` (in em) that would
close the remaining width gap. The contact sheet stacks the mockup's line above
each candidate at matched x-height; the overlays composite mock (red) against
candidate (green), so aligned ink is yellow.

Read it like this:

- **A candidate needing near-zero tracking is the right family.** One that needs
  `-0.05em` is the wrong shape: its advances are too wide, and squeezing them
  wrecks the letter rhythm even when the total width matches. Pick the family
  whose natural width is closest, then use tracking only for the last few pixels.
- Confirm with the overlay. Roboto at `+0.4%` and `-0.01em` beat Inter at `+12%`
  and `-0.06em` decisively on a real design, even though both are grotesques.
- Use `--cap 15` instead of `--xh` when the sample is all capitals.
- **Italic is a separate candidate, not a style of the roman.** Spec syntax is
  `Family:600:italic`, and a family that ships roman only cannot supply the
  italic, so test them separately: one line of the mockup per face. Designs
  routinely pair a display serif with an italic from a *different* family, and a
  reference-guided build found exactly that — Caslon roman, Playfair italic. Fitting
  one font-size to both would have been wrong by 14%.
- Do the same for each distinct size class (display, body, nav, small labels).
  Designs routinely set one family for display and another for text, and small
  labels are often tracked open: **+0.10em to +0.13em on stats and small caps is
  normal, not a mistake.** If a candidate needs a huge positive tracking, that is
  usually correct — check the crop before dismissing it.

## Step 4 — Lay out on a proportional grid

Express every measured pixel as a fraction of the mockup's width so the design
scales linearly and the mockup match holds at any viewport:

```css
html {
  /* 1rem = 100px at a 1536px viewport: design px / 100 = rem */
  font-size: calc(100vw / 15.36);
}
```

Then a measured 24.7px becomes `0.247rem` and reads as a fraction of the design
width. Derive the divisor from the mockup: `100 / mockup_width_px` inverted, i.e.
`100vw / (mockup_width_px / 100)`.

**A trap worth knowing:** `calc(100vw / 1536 * 100px)` is invalid — it multiplies
a length by a length. CSS rejects it silently and `rem` falls back to 100% of the
initial font-size, so the whole page renders at 16px and looks "broken but
plausible". If everything is tiny, check this first.

Keep vertical rhythm in explicit margin variables that you can solve for, one
element at a time:

```css
.hero__body { padding: 0.52rem 0 0 var(--inset); }
.eyebrow    { margin: 0; }
.headline   { margin: 0.275rem 0 0 0.10rem; }
.sub        { margin: 0.29rem 0 0; }
.actions    { margin: 0.29rem 0 0; }
.stats      { margin: 0.66rem 0 0; }
```

Anchor absolute-positioned decorations (map pins, badges) on the **icon's ink
box**, not on the flex container's centre. A two-line label must not be able to
move the icon:

```css
.pin {
  position: absolute;
  display: flex;
  align-items: flex-start;   /* label hangs from the icon's top */
  gap: var(--gap);
}
.pin__icon { width: var(--iw); height: var(--ih); }
.pin__label { margin-top: var(--label-top); }
```

Give each pin `left`/`top` equal to its icon's measured top-left corner as a
percentage of the mockup, and size the SVG with a viewBox exactly as large as its
ink so its box and its ink coincide. Avoid `object-fit`-style guesswork and avoid
`translateY(-50%)`, which couples the icon to the label's height.

For an absolutely positioned background `<img>`, use `inset: 0` **without** `width`/`height`. Setting all three over-constrains the box, and a percentage height
against an auto-height containing block does not resolve the way you expect — the
symptom is a plate that ends partway down the hero.

### Line breaks come from the measure, not the markup

The obvious way to reproduce a headline that breaks after "Vanessa Bell and" is
one `<span class="ln">` per line, `display: block`. It matches the mockup and it
is wrong: the design's breaks are an *accident of its column width*, and encoding
them in the DOM means the element stops being a headline. Edit the text and the
layout lies; and on a phone each span still forces the desktop's break, so the
type cannot reflow.

Set a measure instead and let the browser wrap. Because the intended breaks are a
*window* — if the longest line measures L and the first word of the next line is
W, anything in `[L, L + W)` breaks the same way — the width is solvable rather
than guessable:

```
python3 tools/unwrap.py --selector .headline     # reads the .ln spans, then removes them
```

It measures the real break points in the browser (per character, so exact),
sweeps the width, and writes the midpoint of the valid window into the rule. Five
builds were converted this way and every desktop MAE came back **identical to two
decimal places** — the same pixels, from markup that flows.

Two details the sweep has to get right, both learned by getting them wrong:

- **Sweep `width`, not `max-width`.** `max-width` can never exceed the containing
  block, so a line that needs to be wider than its column (build 24's needs
  1452px in a 1456px column, and the substitute typeface was 5px wider) looks
  unreachable at every value. When the answer exceeds the parent, the tool emits
  `width` so the block may overflow, which is what the mockup does too.
- **Clear `white-space: nowrap` while measuring**, or every width looks identical.
  A `nowrap` on the element is precisely what has to be deleted from the CSS.

The mobile layer must then neutralise the desktop measure, or it inherits a value
in poster rem: `max-width: 9.04rem` is 145px at a 16px root.

## Step 5 — Iterate: render, diff, fix the biggest thing

```bash
python3 tools/shot.py --label it03
```

Writes `shots/it03.png`, a side-by-side, a vertical stack, an edge overlay (mock
edges in cyan, render edges in red) and prints overall MAE plus a 4x3 grid of MAE
by region. Keep every iteration — the sequence is the record of what changed.

Then get the numbers:

```bash
python3 tools/landmarks.py --render shots/it03.png
```

It measures the same named regions on both images and prints `dL dT dW dH` per
element, flagging anything off by 4px or more. This is the workhorse.

How to read and act on it:

- **`dT` is cumulative.** Fix vertical positions top-down, adding each `dT` to the
  margin of the element *above* it. Correcting `.headline` moves `.sub` and
  everything after it, so re-measure after each change instead of applying all
  the deltas at once.
- **`dL` on every element, all the same sign, means the gutter is wrong.** Fix
  `--pad` once, not each element.
- **`dL` off on one element only** is that element's own margin or inset.
- **A delta exactly at a region boundary means you were clipped.** If `dL` is `-27`
  and the region's `x0` is 1120 while the render reports 1147, the render is fine
  and your region is wrong. Widen the region. The same goes for `dW` when an
  element's ink touches the edge.
- **Elements that are always slightly too wide need tracking, not padding.**
  Divide the width error by the number of gaps to get the per-gap change, then
  convert to em.
- **Do not infer button text width from the button box.** Measure the dark ink
  inside the cream rectangle (`measure.py --invert`) — the padding is what you
  have left over, and it is usually smaller than it looks.

Regions are **per design** and belong in the project, not in the tool:
`landmarks.py --regions regions.json` takes `{"name": [x0,y0,x1,y1,thresh,mode]}`.
Derive them from the measurements you already took. The defaults shipped in the
tool are one hero's, and reusing them on a different design reports confident
nonsense — a card title that "grew 185px" because the card was 163px lower than
the region assumed, so the region was reading bare background.

`--cols` splits a region into column runs so you can align nav items, letterspaced
labels and stat lines one by one:

```bash
python3 tools/landmarks.py --render shots/it03.png --cols nav,stats
```

When the background makes measurement noisy, hide the decorations rather than
shrinking the regions — overlapping regions are the main source of phantom
deltas:

```bash
python3 tools/shot.py --label it03c --hide ".notes,.pins"
```

### Choosing the next fix

Fix the largest error first, weighted by visual area. Gutter and vertical rhythm
errors are cheap and shift everything, so do them before per-element widths. A
`dW` of 30px on the headline matters far more than a 5px offset on a map pin.

### When the mockup is internally inconsistent

Mockups — especially AI-generated ones — are sometimes not reproducible. Real
examples encountered: a headline whose third line is 5% wider per glyph than the
first two at the same x-height, so **no** combination of font-size and tracking
fits all three lines; a map whose street labels place landmarks in the wrong
relative positions. Fit the dominant mass (body lines over the last line, the
whole layout over one stray label) and write down what you left unmatched. Chasing
internal inconsistency with global parameters makes the other 90% worse.

## Step 6 — Small screens

The proportional grid reproduces the mockup at its reference width and scales
down proportionally — which is correct for a wide hero and wrong for a phone,
where a 113px headline becomes unreadable. Do not try to fix this by adjusting the
vw divisor: that trades one broken width for another. Re-compose instead, in one
breakpoint, with the grid switched off:

```css
@media (max-width: 900px) {
  html { font-size: 16px; }          /* leave the proportional grid */
  .headline { font-size: clamp(36px, 8.6vw, 76px); line-height: 0.94; }
  /* ...sane mobile sizes for each element... */
  .pins, .notes { display: none; }
  .hero__scrim { /* cover-fitting 16:9 into portrait zooms hard: darken more */ }
}
```

Be honest in your report about this: the mockup match holds at the reference
width, and below the breakpoint the page is a departure from it, not a match.

### The failure this prevents is silent

`1rem = calc(100vw / 15.36)` is right for desktop measurement and catastrophic on
a phone: at 390px one rem is 25px, so `0.25rem` body copy renders at **6px** and
the page becomes a 25%-scale poster with empty space under it. Nothing errors,
nothing overflows, and the desktop diff cannot see it — it only appears at a
width you never looked at. Always render at 390 before calling a build done.

### Two coordinate systems, not one scaled one

Mobile needs a real type scale, and the desktop rem values are meaningless there.
Do not scale them linearly — that is what produces the 6px copy. Compress them:

```
phone_px = 16 * (desktop_px / 25) ** 0.6      clamped to [11, 46]
```

25px → 16px, 110px → 43px, 15px → 11.8px. Ordinal relationships survive (a
headline still dwarfs a caption) and the range collapses. `tools/responsive.py`
reads the real computed sizes off the 1536px render and emits the whole layer,
including un-absolutising the poster's boxes and stacking its columns. Treat its
output as a first draft, never as the answer — and never point it at
a hand-edited `mobile.css`, because it overwrites it.

### The viewport is the measure

Two habits from desktop typography have to be dropped on mobile, and both look
like good practice until you see the result:

- **No `ch` caps.** `max-width: 34ch` is about 280px — *narrower* than a 390px
  container, so at phone width it does nothing but leave a ragged right edge, and
  at 768 it forces a 280px column into a 732px viewport. Type runs to the
  container edge; the container is the measure. A reading-measure limit is a
  desktop device for a 40-70ch column, not a mobile one.
- **Do not force short phrases onto separate lines.** A footer note or a fact
  strip is a run of text, not a list of records: `display: block` on each child
  turns three phrases into three awkward lines. Let it wrap —
  `display: flex; flex-wrap: wrap` — and it will use one line when there is room
  and break where it must. Only genuine records (table rows, cards with internal
  structure) get stacked.

And one trap that produces the exact symptom those two fix:

- **Neutralise desktop measures, do not merely omit your own.** The desktop
  `max-width: 7.2rem` is 115px at a 16px root. Dropping the mobile override
  re-exposes it and the headline renders one word per line — which reads like a
  font-size bug and is not one. Every element that is width-constrained at the
  reference width needs an explicit `max-width: none` (and `width: auto` where it
  had a fixed width) in the mobile layer. `responsive.py` emits this as a
  "measures" section for exactly this reason; treat it as mandatory, not tidying.

A detail that follows: **separators must survive the wrap.** A `border-right`
divider on a flex item that wraps draws a tall rule down its side. Use a
pseudo-element separator instead, and a *general* sibling selector
(`span ~ span::before`) — the adjacent one (`span + span`) silently matches
nothing when a divider element sits between the items, which is how a working
rule produces no separators at all.

### Four things that have to be decided, not derived

1. **The plate cannot become a mobile band.** A plate is the *whole* desktop
   background — panel plus artwork side by side. Cropping it to a portrait band
   shows a slice of both halves. Extract the artwork region into its own asset
   (`im.crop(...)` from the comp, the same move used when the plate disagrees
   with the comp) and lead the page with that.
2. **Full-bleed designs keep their photograph** as a fixed background with an
   *additional vertical* scrim: the comp's own falloff is horizontal, and type
   that sat in the calm half on desktop now sits over the busiest part of a
   portrait crop.
3. **The bottom bar becomes content.** Anything `position: absolute; bottom: 0`
   is pinned to a viewport edge that no longer exists; make it static and let its
   items stack into a fact list.
4. **Tables become records.** A four-column table at 390px is unreadable; give
   each row a grid of `28px minmax(0,1fr) auto` with the number, the name, the
   badge, and the title on a second line.

### Traps, all of them found by looking at 390px

- **`display: inline` on line spans concatenates the text.** A headline built
  from `<span class="ln">` per line has no whitespace between the spans, so
  making them inline to allow wrapping produces "andDuncan". Keep them `block`
  and set `white-space: normal` to let each line wrap *within* itself.
- **A plain `1fr` will not shrink below its content.** In a stacked record, the
  fixed badge column pushes the badge off the right edge; use `minmax(0, 1fr)`.
- **Explicit `td` widths from the desktop table survive** into the mobile grid
  and overflow their tracks. Reset `width: auto !important` on the cells.
- **`white-space: nowrap` is inherited by design decisions made for desktop.**
  Nav rows, buttons and eyebrow labels need it released or they clip.
- **A logo and a five-item nav cannot share one 390px row.** Stack the header;
  let the nav scroll horizontally rather than shrink it below 12px.
- **Tap targets**: buttons go to `min-height: 48px` and full width when they are
  the primary action; a text link beside one needs `white-space: nowrap` and
  breathing room, not equal footing.

### Verify with numbers, at three widths

```
python3 tools/mobile_qa.py --root ../.. --widths 360,390,768
```

It reports, per build: the **character-weighted median** font size of text,
horizontal overflow, and the smallest tap target. The weighting matters — an
unweighted median puts a page of 11px uppercase labels in the same bucket as a
page of 6px body copy, and the two are opposite problems. Below ~13px weighted,
the build has not been adapted. Anything with `hscroll > 0` is broken regardless
of how it looks.

## Tool reference

| tool | what it does |
|---|---|
| `measure.py` | ink boxes, row/column splits, ink and background colours |
| `inpaint.py` | recover the background plate by painting the type out |
| `genimg.py` | generate a raster asset via OpenRouter `/api/v1/images`; `--ref` for image-to-image, `--background transparent` for cut-outs |
| `matchplate.py` | rank-based tone/colour match of an asset onto the plate |
| `tone.py` | duotone an asset onto an explicit two-stop ramp |
| `fontspec.py` | x-height-normalised font identification, sheet + overlays;
`--weights` sweeps the weight axis, `wt x` ranks stroke against the mock |
| `stroke.py` | stem/cap and ink coverage, mock vs render — the only reliable
weight check; the MAE cannot see weight |
| `survey.py` | first pass on a new mockup: palette, ground polarity, ink bands with column splits |
| `unwrap.py` | strip hard-coded line breaks and solve for the measure that reproduces them |
| `responsive.py` | generate a first-draft mobile layer from the computed desktop styles |
| `mobile_qa.py` | per-build, per-width: weighted median text size, overflow, tap targets |
| `shot.py` | render, screenshot, side-by-side, stack, edge overlay, MAE grid |
| `landmarks.py` | per-element `dL/dT/dW/dH` between mockup and render |

## Condensed display type

When a numeral or wordmark is much narrower than the family's normal width, do not
reach for `transform: scaleX` first. Check whether the family has a **variable width
axis** and drive that with `font-stretch`:

```html
<link href="...css2?family=Archivo:wdth,wght@62..125,700..800&display=block">
```
```css
.giant { font-stretch: 62%; }   /* the axis minimum, not an arbitrary number */
```

`font-stretch` below the axis minimum clamps silently, so if two different values give
identical output you have hit the floor — verify by measuring a glyph, not by reading
the CSS back.

A real width axis keeps the stem weights correct, which is exactly what `scaleX`
ruins: horizontal scaling thins the vertical stems by the same percentage, and at
300px that reads as squeezed rather than condensed. Use the axis for the bulk of the
condensation and `scaleX` only for the residual. Measured here: the mockup's `3` was
180px at cap 358; the family's normal width gave 266, the axis floor (62%) gave 191,
and `scaleX(0.94)` for the last 6% gave 180 exactly. A 6% squeeze is invisible; a 32%
one would not have been.

The layout risk of `scaleX` is also smaller than it looks **when the element is
absolutely positioned and clipped**, because a transform does not affect layout, so
nothing else can move. It is dangerous on inline text that has to reflow.

## Reusing a previous build

When a new mockup is a **variant** of one you have already built — same brand, same
plate, same pins, different logotype or stat layout — copy that build and correct it
rather than starting again. Measure the new mockup only where it differs, and let
`landmarks.py` confirm that everything you did *not* touch still lands. A map-hero
variant took 4 cycles this way against 12 for the original; the risk is copying a
number that was only true for the first design (this one wanted the same face at a
smaller size and *positive* tracking where the original needed negative), so
re-derive the type metrics every time even when you reuse the layout.

`genimg.py` reads `OPENROUTER_API_KEY` from the environment (or a
`config.json` with `openrouter_api_key`), and `IMAGE_MODEL` for the model id.

## Measured results across a batch

Nine 1536x864 heroes from one design system, built with this workflow, with the
mockup's own plate used wherever one existed:

| design | MAE | dominant error |
|---|---|---|
| split panel + concierge card | 13.4 | italic face differs from the mockup's |
| map hero (variant) | 20.4 | text antialiasing over a textured plate; line 3 inconsistent |
| full-bleed photo + serif | 18.3 | serif descender depth |
| two-panel + stat bar | 12.0 | text antialiasing only |
| schematic + mono readout | 16.9 | clipped numeral's glyph width |
| photo + mono labels | 16.6 | headline descender depth |
| dark copy + cream list | 20.6 | first headline line's mixed roman/italic width |
| blueprint + dimension lines | 21.0 | drawn furniture; line 2 set tighter than line 1 |
| street photo + italic accent | 15.6 | text antialiasing over a busy photo |

Two things are worth reading off that table. The failures cluster on **typeface
shape** (descender depth, italic slope, weight) rather than on layout — every layout
in the batch landed within a few px. And the worst scores are on the designs with
the most *drawn furniture* (dimension lines, mixed roman/italic within a line),
which is what a raster diff punishes hardest and a viewer notices least. Say which
of the two you optimised for.

## Environment

Nothing exotic: Python with `numpy`, `pillow`, `requests`, `playwright`, and a
Chromium from `playwright install chromium`. Plus a key for the image model.

Image models are billed per image, so write the prompt carefully the first time,
generate one, and compare before generating again.

**When a generation fails, diagnose it before you give up on it.** There are two
very different 402s and they look alike in a log:

- `in_flight_budget_exhausted` with a `Retry-After` header is a *concurrency*
  limit. Wait and retry.
- `limit_source: openrouter_credits` is a *balance* problem. Do not read it as
  zero: check the actual numbers, because "nearly out" and "out" are different
  problems with different answers.

```bash
curl -s https://openrouter.ai/api/v1/credits -H "Authorization: Bearer $K"
curl -s https://openrouter.ai/api/v1/key     -H "Authorization: Bearer $K"
```

`total_credits` minus `total_usage` is the account balance; `limit_remaining` is
the key's own budget, and it is often the smaller of the two.

If the balance looks small but non-zero, find out whether the rejection depends on
the *size* of the request before concluding anything. Cheaper image models are
routinely an order of magnitude below the flagship one, so the answer is often yes:

```bash
python3 tools/genimg.py --model <cheapest-image-model> --out work/try.png \
    --prompt "a flat solid dark square" --aspect 1:1 --resolution 512
```

If that *also* returns `openrouter_credits`, the account is blocked for image
generation regardless of request size and no model substitution will help — stop
retrying and say so, with the numbers. If it succeeds, you have found that the
flag is amount-dependent and can pick a model that fits.

Two different things can be the ceiling and they are easy to confuse:
`total_credits - total_usage` is the **account** balance, while `limit_remaining`
is the **key's own** budget (often a daily cap). A key with budget left against a
drained account fails, and the error names the account, not the key.

Either way, do not declare a known-weak asset final without doing this
diagnosis first. Say which model produced which asset, and why you stopped.

## Pitfalls, collected

- `calc(100vw / 1536 * 100px)` is invalid and fails silently to 16px.
- Canvas text metrics silently report the *fallback* font unless you
  `await document.fonts.load(...)` first. Symptom: every candidate returns
  identical metrics.
- Percentage height plus `inset: 0` plus `height: 100%` on an `img` leaves the
  plate short; use `inset: 0` alone.
- Landmark regions that overlap neighbouring elements, or clip the element they
  are measuring, produce convincing nonsense. Check for ink sitting on a region
  edge before believing a delta.
- Inpainting by repeated blur never fills the middle of a large hole. Grow the
  known region each pass.
- Generated images will contain garbled text if you let them. Ban text explicitly,
  then rebuild every string in HTML.
- A 402 is not always "out of credits". Check the balance and the key's own limit,
  then price the alternatives before abandoning an asset.
- Button padding looks bigger than it is; measure the text ink.
- Optical insets are real: display type often sits a few pixels inboard of the
  body copy's container. Match what you measure per element.
- Small type is frequently tracked open (+0.10em or more). That is a design
  decision, not a measurement error.
- **A first child's top margin collapses out of its section** and shifts the whole
  section, so absolutely positioned children derived from page coordinates land
  wrong by exactly that margin. Symptom: a sibling offset by a constant that
  matches the first element's margin. Give the section `display: flow-root`.
- **The worst case of that collapses out of `body` itself**, and it is near
  invisible: `body` starts at y = the margin, so the margin's own element looks
  correctly placed while every absolutely positioned child is displaced by the
  full margin. A page whose portrait sat 343px low scored a perfectly plausible
  MAE — nothing is missing, only wrong. Check `body.getBoundingClientRect().y`
  ought to be 0; if it is not, the fix is `display: flow-root` on the section
  whose first child carries the margin. `tools/shot.py` now prints a warning.
  Do not trust a render in which that value is non-zero, and do not go looking
  for the cause in the code that looks wrong — the offset is in the parent chain.
- **Position absolutely-children against `body`, not against the section.** If the
  card is `absolute` inside `.hero` and `.hero` starts below a 94px header, then
  `top: 142px` means 236px on the page. Put `position: relative` on `body` and
  measure the card in page coordinates. This bites hardest when `.hero` is
  `position: relative` *only* to hold a `z-index`: the section becomes the
  containing block by accident, and a footer list written as
  `position: absolute; bottom: 0.62rem` anchors to the hero's content height
  instead of the page — landing 200px high, on top of the subhead. Five of the
  thirty-six builds had exactly this.
- **Check containment with `offsetParent`, not by eye.** Any absolute element with
  a `top`/`bottom` whose `offsetParent` is not `BODY` is either intentional
  nesting or this bug:

  ```js
  getComputedStyle(el).position === 'absolute' && el.offsetParent.tagName !== 'BODY'
  ```

  `shot.py` prints a warning listing them on every render. Legitimate hits look
  like a card arrow inside a card, or a scrim inside its hero; a page-scale list
  or footer inside `.hero` is the bug. The fix is to move the element out of the
  section in the HTML, not to add more `position: relative`.
- **The MAE cannot see a small block in the wrong place.** Moving a 93px footer
  list 200px from overlapping the subhead to its correct position changed the
  score by **0.03**. A text block is a tiny fraction of the pixels, so nothing in
  a whole-page diff will catch it — only a rect check or an anchored-to-the-wrong
  -parent check will.
- **`line-height: normal` on a serif heading inflates its box** past its ink, and
  every margin you derived ink-to-ink below it is now wrong. Set an explicit
  `line-height` on every heading *before* solving the margins beneath it — the
  build that skipped this was 163px out on the card.
- **A vertical divider rule often belongs to the column box, not the text.** It can
  also be taller than the text block (one build: 78px of rule against 60px of
  text, starting 13px above the numerals). If the deltas say the rule is off by a
  constant in both directions, you put the border on the padding edge instead of
  the box edge, or 8px of rule is missing outside the text.
- **Do not change font-size and container width in the same step.** A paragraph
  constrained by both will swap its line breaks on you and every width you measure
  after that is a different string. Set the size from the cap height, then set the
  width to force the break the mockup shows, then confirm the *text* of each line
  matches — not just the numbers.
- **MAE can reward the wrong decision.** On a light card of body copy, a slightly
  too-small font that pulls one extra word onto the first line scored a *lower*
  whole-image MAE than the correct size with the correct break, because it put ink
  where the antialiasing already was. When MAE and the landmarks disagree, or when
  MAE improves as you make something measurably worse, believe the landmarks and
  the crop. Compare crops; the eye is the arbiter for "is this the same string".
- **`html { font-size: calc(100vw / N) }` makes 100px the default text size.** Any
  element that forgets to set its own `font-size` inherits the root's — a data
  column came out at 100px and shredded the layout. With a proportional grid,
  *every* text-bearing selector needs an explicit size; there is no safe default.
- **`bottom` on an absolutely positioned box resolves against its containing
  block's height, not the viewport.** A card pinned with `bottom: 35px` landed
  120px too high because `body` was 746px tall, not 864. Anchor with `top` in page
  coordinates instead, and give `body` `overflow-x: hidden` when display type is
  meant to bleed off the right edge.
- **Oversized display numerals are usually wider or taller than the face's own
  proportions.** Solve the font-size from the measured *advance* between glyph
  centres (Inter's digits are 0.636em), then `scaleY` about the baseline for the
  cap height, and re-solve the box origin afterwards — changing the scale moves
  the rendered baseline even though the box has not moved.
- **A landmark whose box is clipped by an image edge cannot validate width.** A
  display numeral that runs off the right of the frame reports the same `x1` in both
  images no matter how wrong its glyphs are — a "perfect" `dW 0` that means nothing.
  For anything that bleeds, measure *inside* it: the x of the first inter-glyph gap,
  or the ink width of the first glyph. Two designs here scored `0,0,0,0` on a clipped
  numeral whose digits were 48% too wide.
- **Check for overflow explicitly; a clipped region hides it.** If a landmark region
  stops at a column boundary, ink that crosses the boundary is simply not counted and
  the element looks fine. One build shipped a headline whose last letter ran into the
  next panel while every landmark was clean. Assert it separately:

  ```js
  // text rect, not element rect: a display:block span is as wide as its container
  [...document.querySelectorAll('.headline .ln, .ledger li')]
    .map(e => { const r = document.createRange(); r.selectNodeContents(e);
                return [e.className, r.getBoundingClientRect().right]; })
    .filter(([, right]) => right > PANEL_EDGE)
  ```

  It should return an empty array. This costs one line and catches the class of bug a
  pixel diff cannot see, because the overflow is dark-on-dark where it crosses.
- **Heavy display type is almost always tracked negative, so a positive result means
  your cap height is wrong.** Fitting a headline at cap 61 asked for `+0.014em`;
  re-measuring the cap at 64 (a `V` clipped by a too-tight region) flipped it to
  `-0.012em`. If a heavy grotesque wants opening up, re-measure the cap first.
- **`fontspec` matches width, not weight — and the MAE does not measure weight at
  all.** This is the sharpest trap in the whole process. A face that is 50% too
  heavy can be tracked to the right width and will score *better* on MAE than the
  correct weight, because its extra ink lands on the mock's antialiased edges. In
  one build, weights 500/550/600/650 of the same family scored 21.23/21.24/21.25/
  21.25 while stems ranged 0.93/0.93/1.08/1.09 of the mock — the metric moved by
  0.02 across a 20% weight change. Worse, the too-heavy 800 scored 20.30, the best
  of all of them, at 1.49x the correct stem.

  So never judge weight from the score. Measure it:

  ```
  python3 tools/stroke.py --a mock.jpg --b shots/it01.png --region x0,y0,x1,y1
  ```

  It reports `stem/cap` for both images and the ratio. Both are normalised by cap
  so a size error cannot read as a weight error, and the verdict bands are ±12%.
  Run it on the display line before you call a build done. `fontspec --weights
  400,500,600,700` adds a `wt x` column that ranks weight the same way while you
  are still choosing the family; pick the row where `dW` is small *and* `wt x` is
  near 1.0, not the row with the smallest `dW`.

- **When no weight of a family fits, the family is wrong.** If the lightest cut is
  ~20% light and the next available weight is ~20% heavy, the problem is the cut,
  not the axis. Two escapes, in order of preference:

  1. **A different cut of the same design.** "Libre Caslon Display" is a hairline
     display optical size; "Libre Caslon Text" is the same family drawn heavier.
     Display vs Text, Display vs Regular, Condensed vs normal — these are different
     *families* to Google Fonts but the same design lineage, and swapping between
     them changes weight far more than the weight axis does.
  2. **A different face at a real bold weight.** One build's serif measured 30% too
     light as `Libre Caslon Display 400`; `Playfair Display 700` matched the stem
     exactly *and* improved the MAE. Prefer this to a stroke.

  `-webkit-text-stroke: 0.024rem` on a 400-only family is the last resort: it does
  hit the stem ratio (it got one build from 0.85 to 1.03) and it does not disturb
  layout, but it bloats the joints of a high-contrast serif. Use it when the family's
  *proportions* are right and only the weight is missing, and note it in the build.

- **The Google Fonts URL must request the weights you use.** A link written as
  `Inter+Tight:wght@500;700;800` silently clamps `font-weight: 600` and synthesises
  every intermediate value, so a weight sweep returns identical renders for every
  value you try. Request a range (`wght@100..900`) whenever you intend to move the
  axis. And a 400-only family will not synthesise bold below 600, so 500 and 550
  render identically to 400 — the gap between "too light" and "too heavy" is real
  and is the signal to change family.

- **Measure the cap from a flat-topped capital, never from the ink band.** A band's
  height includes the descender of whichever letter happens to have one: a headline
  band reading 103 was a cap of 73 plus a `g`. Feeding 103 to `fontspec --cap` made
  every candidate 40% too large and inverted the width comparison, so the *narrowest*
  face looked 5% too wide. Crop to a single `T`/`H`/`E` and measure that.

- **A measurement region must contain the target and nothing else.** A headline
  region that ran on into a table of small mono text pulled the median stem down to
  the table's stroke width and turned a real +50% weight error into a reassuring
  +42%. The region should hold one line of one element; if you cannot crop to that,
  crop narrower rather than trusting the median.
- **A cap measurement far larger than the font implies means overlapping lines.** A
  headline measured at cap 96 when its font-size implied 79 was reading across two
  lines, because `line-height` had been set to 73px for a 110px font. If cap comes out
  impossible, the region is crossing lines, not the font being wrong. Measure the
  pitch from a repeated glyph (the `T` of each line) instead of from ink bands.
- **Sample colour per region, at the top decile, not from an impression.** On a
  dark schematic plate the mono readout looked like a dim teal and was actually a
  light cyan (`#9edad6`); the headline was near-white. One wrong colour across a
  whole readout costs more MAE than several 2px offsets.
- **A typed character can fall back to another font and change size.** A `&middot;`
  separator rendered visibly oversized inside a mono run; give such glyphs an
  explicit `font-size`.
- **Treat an AI-generated grid as texture, not geometry.** One mockup's rules ran
  at a 160px pitch on the left and 166px on the right with doubled horizontal
  lines. Reproduce the effect (a faint gradient or a few positioned rules) and
  spend the iterations on type and layout instead.
- **If the mockup already contains the photograph, crop it out and use it.** Do not
  generate a lookalike: a crop is exact, free and instant, and it is the only
  defensible reading of "reuse the design's own imagery". Generating is for the
  imagery the mockup does *not* hand you — plates, illustrations, icons — and for
  anything whose text you would otherwise bake in.
