Build a Mobile-First Grid and Resilient Signup Form in Plain CSS
System DesignModel answerLast updated
Create your own responsive utility-class grid, an accessible navbar and form, then add robust validation, async submit states, retry rules and telemetry, with no CSS framework.
Task
Build a small page that demonstrates a hand-written, utility-first CSS system. You may not import any CSS framework or library. Everything should be your own code: HTML, CSS and, where necessary, a little JavaScript.
Part 1: Utility system and layout
Design reusable classes for:
- Layout: a centered
container, arow, and column classes (col-*) driven by a 12-unit grid. - Breakpoints: mobile-first, with at least three tiers (for example small, medium, large). A column with no breakpoint prefix applies everywhere, and larger breakpoints override smaller ones.
- Gutters: configurable spacing between columns, including a "no gutter" modifier.
- Nesting: a row placed inside a column must still line up correctly.
- Helpers: spacing (margin/padding), typography (size, weight, alignment), and a visually-hidden class.
Part 2: Accessible components
Using those utilities, build:
- a navbar that collapses to a toggle button on narrow screens,
- buttons,
- text inputs with labels,
- inline validation messages.
Use semantic HTML and make the page usable by keyboard and screen reader users.
Part 3: Failure handling for the form
Extend the form so that it handles problems gracefully:
- Invalid input: client-side validation with clear, field-level messages.
- Async submission failures: the user must see distinct states for loading, success, retryable error (for example network failure or a 5xx response) and non-retryable error (for example a 4xx or a server-side validation rejection).
- Telemetry: describe and implement what you would record about validation failures, submit attempts, outcomes and latency.
What to deliver
Provide the code (or well-structured excerpts) and explain the design decisions: how columns are sized, how breakpoints resolve, how nesting and gutters work, how accessibility is achieved, and how the submission state machine behaves.
Hints
Hint 1
Let each column class set only a custom property such as --span, and have one shared rule convert it to a width with calc(var(--span) / 12 * 100%). Breakpoint variants then only need to change that variable.
Hint 2
For gutters, give columns horizontal padding of half the gutter and give the row the opposite negative margin. Because a nested row sits inside a padded column, the same trick keeps nested content aligned.
Hint 3
Treat submission as a small state machine (idle, submitting, success, retryable-error, fatal-error). Guard against double submits with an in-flight flag rather than the native disabled attribute, announce changes in an aria-live region, and reuse an idempotency key on retries.
Hint 4
Classify errors by cause: network failures, timeouts and 5xx are retryable (with backoff); 4xx and 422 are not, and 422 should map messages back onto specific fields.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach overview
The answer has two halves: a small CSS system built on a few rules that compose well, and a form that behaves predictably when things go wrong.
1. The grid
Three rules do most of the work.
- Rows are flex containers with negative side margins; columns are flex items with side padding. The padding forms the gutter. The negative margin on the row cancels the outer half-gutter so content aligns with the container edge.
- Columns are sized by a variable. Every
col-*class only sets--span. One shared rule on.row > *converts it:
:root { --gx: 1.5rem; --gy: 1rem; }
.container { width: 100%; margin-inline: auto; padding-inline: calc(var(--gx) * .5); }
.row { display: flex; flex-wrap: wrap; margin-inline: calc(var(--gx) * -.5); row-gap: var(--gy); }
.row > * {
flex: 0 0 calc(var(--span, 12) / 12 * 100%);
max-width: calc(var(--span, 12) / 12 * 100%);
padding-inline: calc(var(--gx) * .5);
}
.col-6 { --span: 6; }
@media (min-width: 768px) { .col-md-6 { --span: 6; } }
.g-0 { --gx: 0; --gy: 0; }
- Breakpoints are mobile-first. Unprefixed classes apply at all widths. Prefixed classes live in
min-widthmedia queries placed later in the file. Specificity is equal, so source order lets the widest matching breakpoint win, with no!important.class="col-12 col-md-6"stacks on phones and splits at medium widths and up.
Why this holds up
- Nesting: an inner
.rowapplies its own negative margin against the parent column's padding, so it is flush with the column's content box at every depth. - Gutter control: since the gutter is a variable,
.g-0on one row changes only that row and its descendants through inheritance. - Default fallback:
var(--span, 12)means a column that only hascol-md-6is full width below medium. - Cost: a handful of single-class selectors, so matching is cheap and layout needs no JavaScript. Generate the 12 x B column rules with a preprocessor loop in a real project.
Helpers are plain single-purpose classes (.mt-3, .p-3, .fw-bold, .text-center, .visually-hidden). Use clamp() for fluid type.
2. Accessible components
- Landmarks and skip link:
header,nav,main,footer, plus a skip link that becomes visible on focus. - Navbar toggle: a real
<button>witharia-expandedandaria-controls. Hide the collapsed menu only when JavaScript has added ajsclass to<html>, so the nav works without JS (progressive enhancement). - Forms: every input has a
<label for>. Hints and errors are linked witharia-describedby; invalid fields getaria-invalid="true". - Focus and motion: visible
:focus-visibleoutlines and aprefers-reduced-motionrule that disables transitions. - Contrast: keep text and control colors at WCAG AA ratios.
3. Handling invalid input
- Validate on submit (and on blur after the first attempt) using native constraints (
required,type=email,pattern) plus custom checks. - Render one message per field, inside an element referenced by
aria-describedby. On a failed submit, move focus to the first invalid field and put an error summary in a live region. - Treat client validation as a convenience only. The server remains authoritative, and its field errors (HTTP 422) are mapped back to the same message slots.
4. Submission state machine
States: idle -> submitting -> success | retryableError | fatalError, and retryableError -> submitting on retry.
| State | UI | Notes |
|---|---|---|
| submitting | spinner, "Sending..." | announced via aria-live="polite" |
| success | confirmation, form reset or cleared | focus moves to the confirmation |
| retryableError | "Something went wrong, try again" with a Retry button, input preserved | network error, timeout, 5xx, 429 |
| fatalError | field-level messages or a "contact support" notice | 400, 401/403, 404, 422 |
Key details:
- Prevent double submits with an in-flight flag and
aria-disabled="true"on the button. Avoid nativedisabledwhile loading, since it drops focus and can hide the control from assistive tech. - Idempotency key: generate a UUID per logical submission and send it as a header. Reuse it on retries so the server never creates duplicates.
- Timeout and cancel: use
AbortControllerwith a timeout (say 10 s) and treat the abort as retryable. - Automatic retry: for retryable cases, optionally retry up to 2-3 times with exponential backoff and jitter (for example 500 ms, 1 s, 2 s), honoring
Retry-Afteron 429/503. After that, hand control to the user with a manual Retry button. - Never lose user input on failure.
async function submit(form) {
if (inFlight) return;
if (!validate(form)) { track('validation_failed'); return; }
inFlight = true; setState('submitting');
const key = form.dataset.key ||= crypto.randomUUID();
const t0 = performance.now();
try {
const res = await fetch('/api/signup', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key },
body: JSON.stringify(Object.fromEntries(new FormData(form))),
signal: AbortSignal.timeout(10000),
});
if (res.ok) { setState('success'); delete form.dataset.key; }
else if (res.status === 422) { showFieldErrors(await res.json()); setState('fatalError'); }
else if (res.status >= 500 || res.status === 429) setState('retryableError');
else setState('fatalError');
track('submit_result', { status: res.status, ms: performance.now() - t0 });
} catch (e) {
setState('retryableError');
track('submit_result', { status: 'network', ms: performance.now() - t0 });
} finally { inFlight = false; }
}
5. Telemetry
Send events with navigator.sendBeacon so they survive page unloads. Record:
validation_failedwith field names and rule IDs (never field values),submit_attemptwith attempt number,submit_resultwith outcome class, HTTP status, latency, and retry count,retry_clickedand eventuallyabandoned(user left in an error state).
Include a session ID and the idempotency key for correlation. Avoid personal data, respect consent settings, and sample high-volume events. Useful dashboards: error rate by class, p95 latency, and the validation rule that fails most often (a signal of confusing UX).
Common mistakes
- Using
!importantto win breakpoint conflicts instead of relying on source order. - Forgetting the negative row margin, which misaligns content with the container edge.
- Using
disabledon the loading button, losing focus and screen reader context. - Retrying non-idempotent requests without a key, causing duplicate records.
- Treating every failure as retryable, so users keep retrying a request that can never succeed.
- Clearing the form on error.
- Logging raw field values in telemetry.