Frontend development · Intermediate · 22 min
Build skeleton loading screens in CSS
By Padding · Updated 18 Nov 2026
Modern browsers · CSS Animations Level 1 and WAI-ARIA 1.2 · checked in Chromium 159
You will build a skeleton for the Larkfield Clinic My appointments list that has the same shape as the loaded rows, keeps quiet for screen readers, stops shimmering under reduced motion, and passes a browser check for zero layout shift when the data arrives.
On this page
A skeleton screen is a grey outline of content that has not arrived yet. Done well, it tells people what kind of thing is coming and where it will appear, so the wait feels shorter and nothing on the page moves when the real content lands. Done badly, it is a decoration with its own problems: grey bars that are a different height from the text they stand in for, so the whole page jumps when the data arrives; a screen reader that reads out a list of empty items; and a shimmer that never stops for someone who has asked their device for less motion.
This tutorial builds the version that avoids all three, for one screen of the Larkfield Clinic booking app, the fictional community clinic used across the design track. A patient opens the My appointments tab and the app fetches their bookings. They have three: the Nurse appointment on Tuesday 9 December at 10:30, a Blood test on Thursday 18 December at 09:20 and a Medication review on Monday 5 January at 14:00. While the request is in flight, the list shows three skeleton rows.
The method is one rule: the skeleton row is the real row with the text replaced. It uses the same elements, classes, padding and line heights, so the browser lays it out at exactly the size of the row that replaces it. You will prove that with a script that measures layout shift, rather than by eye.
The colours are the Larkfield variables from the high-fidelity design: text #1B1F24, text-muted #5A6270, surface #FFFFFF, canvas #F6F7F8 and line #D5D9DF. Everything is plain HTML, CSS and a few lines of JavaScript, with no framework.
Step 1 · Write the page markup
Make a demo folder and the page. It holds a heading, a hidden status line, the list with three skeleton rows already inside it, a help line under the list, and a <template> holding one real row for the script to copy:
mkdir -p ~/skeleton-demo
cd ~/skeleton-demo
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My appointments · Larkfield Clinic</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<h1 id="appts-heading">My appointments</h1>
<p id="appts-status" class="visually-hidden" role="status"></p>
<ul id="appts" class="appts" aria-labelledby="appts-heading" aria-busy="true">
<li class="appt appt--skeleton" aria-hidden="true">
<p class="appt-service"><span class="bone" style="--w: 55%"></span></p>
<p class="appt-when"><span class="bone" style="--w: 45%"></span></p>
<p class="appt-where"><span class="bone" style="--w: 70%"></span></p>
</li>
<li class="appt appt--skeleton" aria-hidden="true">
<p class="appt-service"><span class="bone" style="--w: 40%"></span></p>
<p class="appt-when"><span class="bone" style="--w: 50%"></span></p>
<p class="appt-where"><span class="bone" style="--w: 70%"></span></p>
</li>
<li class="appt appt--skeleton" aria-hidden="true">
<p class="appt-service"><span class="bone" style="--w: 60%"></span></p>
<p class="appt-when"><span class="bone" style="--w: 45%"></span></p>
<p class="appt-where"><span class="bone" style="--w: 70%"></span></p>
</li>
</ul>
<p class="help">Need to change a booking? Call 01234 567 890</p>
</main>
<template id="appt-row">
<li class="appt">
<p class="appt-service"></p>
<p class="appt-when"></p>
<p class="appt-where"></p>
</li>
</template>
<script src="app.js" defer></script>
</body>
</html>
HTMLThree choices in this markup matter later:
- The skeleton rows are in the HTML, not added by the script. They appear on the very first paint, before any JavaScript has downloaded. On a low-end Android phone on a slow prepaid connection, that can be a second or more of useful outline instead of a blank screen.
- Each skeleton row uses the same classes as the real row in the template (
appt,appt-service,appt-when,appt-where), plus one modifier,appt--skeleton. Inside each paragraph is a.bone, an empty span that becomes a grey bar. The--wcustom property gives each bar a different width so the rows do not look like a barcode. - The accessibility attributes are already there:
aria-hidden="true"on each skeleton row,aria-busy="true"on the list and an emptyrole="status"paragraph. A later step explains them and makes the script update them.
Check it worked
Open index.html in your browser. From a terminal on a desktop machine, open index.html on macOS or xdg-open index.html on Linux does it, or drag the file into a browser window. You see the heading "My appointments", three bullet points with nothing after them and the help line. The empty bullets are the skeleton rows before any CSS. The browser's console reports that app.js is missing, which you fix in the next step.
Step 2 · Style the loaded row and show the data
Build the real row first. The skeleton copies whatever the real row does, so the real row has to be settled before you draw its outline. Write the stylesheet:
cd ~/skeleton-demo
cat > style.css <<'CSS'
:root {
--text: #1b1f24;
--text-muted: #5a6270;
--surface: #ffffff;
--canvas: #f6f7f8;
--line: #d5d9df;
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--canvas);
color: var(--text);
font-family: system-ui, sans-serif;
font-size: 1rem;
line-height: 1.5rem;
}
main { max-width: 26rem; margin: 0 auto; padding: 1rem; }
h1 { font-size: 1.75rem; line-height: 2.125rem; margin: 0 0 1rem; }
.appts {
display: grid;
gap: 0.75rem;
margin: 0 0 1.5rem;
padding: 0;
list-style: none;
}
.appt {
padding: 1rem;
border: 1px solid var(--line);
border-radius: 0.75rem;
background: var(--surface);
}
.appt p { margin: 0; }
.appt-service { font-weight: 600; }
.appt-where,
.help {
color: var(--text-muted);
font-size: 0.875rem;
line-height: 1.25rem;
}
.help { margin: 0; }
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
margin: -1px;
padding: 0;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
border: 0;
}
CSSEvery line height is a fixed length (1.5rem, 1.25rem) rather than a multiplier. That makes each line of a row a known height whatever is inside it, which is the property the skeleton depends on.
Now the script. It stands in for a network request with a timer, so you can control the wait from the address bar: ?delay=5000 waits five seconds, and ?hold never loads, which keeps the skeleton on screen while you style it.
cd ~/skeleton-demo
cat > app.js <<'JS'
const appointments = [
{ service: 'Nurse appointment', when: 'Tue 9 Dec, 10:30', length: '15 min' },
{ service: 'Blood test', when: 'Thu 18 Dec, 09:20', length: '10 min' },
{ service: 'Medication review', when: 'Mon 5 Jan, 14:00', length: '20 min' },
];
const params = new URLSearchParams(location.search);
const delay = Number(params.get('delay') ?? 2000);
const list = document.getElementById('appts');
const rowTemplate = document.getElementById('appt-row');
// Stands in for fetch('/api/appointments').then((r) => r.json())
function fetchAppointments() {
return new Promise((resolve) => setTimeout(() => resolve(appointments), delay));
}
function render(items) {
const rows = items.map((a) => {
const row = rowTemplate.content.firstElementChild.cloneNode(true);
row.querySelector('.appt-service').textContent = a.service;
row.querySelector('.appt-when').textContent = `${a.when} · ${a.length}`;
row.querySelector('.appt-where').textContent = 'Larkfield Clinic, 14 Mill Lane';
return row;
});
list.replaceChildren(...rows);
}
if (!params.has('hold')) {
fetchAppointments().then(render);
}
JSreplaceChildren removes the skeleton rows and inserts the real ones in one operation, so there is never a frame with both, or with neither.
Check it worked
Reload the page. For two seconds the list shows three white cards with only padding inside, then three appointments appear: "Nurse appointment" in bold, "Tue 9 Dec, 10:30 · 15 min" under it and "Larkfield Clinic, 14 Mill Lane" in smaller grey text. The bullets have gone. The help line jumps down when the appointments arrive, because the empty cards are shorter than the full ones. That jump is what the next step removes.
Step 3 · Shape the skeleton to match the row
An empty paragraph has no height, which is why the cards were thin. The bone fixes that. It is an inline block inside the paragraph, so the paragraph keeps its own line box, at the same fixed line height as the text it stands in for. The bar is drawn shorter than the line and centred in it, the way a line of text has space above and below its letters:
cd ~/skeleton-demo
cat >> style.css <<'CSS'
.bone {
display: inline-block;
width: var(--w, 50%);
height: 0.75em;
vertical-align: middle;
border-radius: 0.25rem;
background: var(--line);
}
CSSThe bar's height is in em, so it scales with each paragraph's font size: slightly shorter in the smaller .appt-where line, as the real text is. Its width is a percentage of the row, set by --w in the markup. Do not give the bones fixed pixel heights or margins of their own. The moment the skeleton has its own sizes, it stops matching the row, and any later change to the real row's typography makes the two drift apart.
One limit to know about: this matches the row only while each real line fits on one line. A longer service name, a larger text setting on the phone, or a translation can make a line wrap, and that row then grows by one line when it loads. If your text often wraps, for example a French or Hausa version of the app where labels run longer, give the bone two lines for that field, or set a min-height on the row that covers the common case.
Check it worked
Open index.html?hold (type ?hold at the end of the address in the address bar). Each card now has three grey bars of different widths, the third one slightly thinner. Then open index.html?delay=5000, watch the help line while the appointments arrive, and it stays exactly where it is. To compare numbers, run document.querySelector('.appt').offsetHeight in the browser console on both versions: it reports the same height for the skeleton row and the loaded row.
Step 4 · Add a shimmer
A soft highlight that sweeps across the bars tells people the page is still working, not stuck. Draw it on a pseudo-element and move it with transform, which the browser can animate without recalculating layout:
cd ~/skeleton-demo
cat >> style.css <<'CSS'
.appt--skeleton .bone {
position: relative;
overflow: hidden;
}
.appt--skeleton .bone::after {
content: "";
position: absolute;
inset: 0;
background: linear-gradient(90deg, transparent, rgb(255 255 255 / 0.65), transparent);
transform: translateX(-100%);
animation: shimmer 1.6s ease-in-out infinite;
}
@keyframes shimmer {
to { transform: translateX(100%); }
}
CSSoverflow: hidden on the bone clips the highlight to the bar, and inset: 0 makes the highlight exactly the bar's size before it moves. A common alternative animates background-position on a wide gradient. It looks the same, but transform is the cheaper property for the browser to animate, which matters on a low-end phone that is also busy parsing the response.
Keep the shimmer subtle. A strong flash across several rows is distracting, and the person is waiting for their appointments, not watching the loading state.
Check it worked
Open index.html?hold. A pale highlight sweeps from left to right across each grey bar about every one and a half seconds, and stays inside the bar's rounded edges. The cards themselves do not move or change size.
Step 5 · Stop the shimmer under reduced motion
Some people set their device to reduce motion because animation makes them dizzy or makes it hard to concentrate. Browsers pass that setting to CSS as the prefers-reduced-motion media feature. For a skeleton, the right response is to stop the sweep entirely and leave plain grey bars, which still show that content is coming:
cd ~/skeleton-demo
cat >> style.css <<'CSS'
@media (prefers-reduced-motion: reduce) {
.appt--skeleton .bone::after {
animation: none;
display: none;
}
}
CSSdisplay: none removes the highlight as well as the animation, so the bars do not keep a frozen white streak at one edge.
Check it worked
Switch reduced motion on, then open index.html?hold again. On macOS it is System Settings, Accessibility, Display, Reduce motion; on Windows 11, Settings, Accessibility, Visual effects, Animation effects (off); on Android, Settings, Accessibility, Remove animations (the exact path varies by phone maker). In Chrome and Edge you can also emulate it without changing your system: open DevTools, press Ctrl+Shift+P (Cmd+Shift+P on macOS), type "rendering", open the Rendering panel and set "Emulate CSS media feature prefers-reduced-motion" to reduce. The bars are plain grey and nothing moves. Turn the setting off and the sweep returns.
Step 6 · Keep the skeleton silent for screen readers
A sighted person glances at grey bars and understands. A screen reader user would hear "list, 3 items" followed by three empty items, which sounds like a broken page. The markup from the first step already handles most of this:
aria-hidden="true"on each skeleton row removes it from the accessibility tree, so the bars are never read out.aria-busy="true"on the list tells assistive technology the list is being updated and is not ready yet. Support varies between screen readers, so treat it as a helpful extra, not the only signal.- The
role="status"paragraph is a polite live region: when its text changes, screen readers read the new text at the next pause, without moving focus. Thevisually-hiddenclass keeps it off screen but in the accessibility tree.
The script now has to use them. Replace app.js with the final version. It says "Loading appointments" when the request starts, and when the rows are in it sets aria-busy to false and says how many appointments loaded:
cd ~/skeleton-demo
cat > app.js <<'JS'
const appointments = [
{ service: 'Nurse appointment', when: 'Tue 9 Dec, 10:30', length: '15 min' },
{ service: 'Blood test', when: 'Thu 18 Dec, 09:20', length: '10 min' },
{ service: 'Medication review', when: 'Mon 5 Jan, 14:00', length: '20 min' },
];
const params = new URLSearchParams(location.search);
const delay = Number(params.get('delay') ?? 2000);
const list = document.getElementById('appts');
const status = document.getElementById('appts-status');
const rowTemplate = document.getElementById('appt-row');
// Stands in for fetch('/api/appointments').then((r) => r.json())
function fetchAppointments() {
return new Promise((resolve) => setTimeout(() => resolve(appointments), delay));
}
function render(items) {
const rows = items.map((a) => {
const row = rowTemplate.content.firstElementChild.cloneNode(true);
row.querySelector('.appt-service').textContent = a.service;
row.querySelector('.appt-when').textContent = `${a.when} · ${a.length}`;
row.querySelector('.appt-where').textContent = 'Larkfield Clinic, 14 Mill Lane';
return row;
});
list.replaceChildren(...rows);
list.setAttribute('aria-busy', 'false');
status.textContent = `${items.length} appointments loaded`;
}
status.textContent = 'Loading appointments';
if (!params.has('hold')) {
fetchAppointments().then(render);
}
JSThe status paragraph is in the HTML from the start and the script only changes its text. That order matters: many screen readers ignore a live region that is added to the page already filled in, and only announce changes to one they have seen before.
In a real app, also handle the request failing. Replace the skeleton with a message and a way to try again, and put that message in the status region too. Announce errors and notices with a live region covers the error side.
Check it worked
Open index.html?hold and open DevTools. In Chrome or Edge, select the list in the Elements panel and open the Accessibility pane; in Firefox, use the Accessibility panel. The skeleton rows are not in the accessibility tree, and the status paragraph's text is "Loading appointments". Load index.html without ?hold: after two seconds the status text reads "3 appointments loaded" and the list has aria-busy="false". If you have a screen reader (VoiceOver on macOS or iOS, NVDA on Windows, TalkBack on Android), you hear "Loading appointments" and then "3 appointments loaded", and never the empty rows.
Step 7 · Check for layout shift with a script
Watching the help line by eye catches a big jump but not a two-pixel one. Browsers based on Chromium measure layout shift for you through the Layout Instability API, the same measurement behind the Cumulative Layout Shift score: each time a visible element moves without the user having just interacted, the browser records a layout-shift entry with a score. A skeleton that matches its content scores zero.
Install Playwright, which drives a real browser from a script, into the demo folder. --with-deps also installs the system libraries Chromium needs on Linux, which can ask for your password:
cd ~/skeleton-demo
npm init -y > /dev/null
npm install playwright@1.65.1
npx playwright install --with-deps chromiumThe check loads the page on a phone-sized screen, records every layout shift from the first paint, and asserts what a patient would see and hear before and after the data arrives. Then it makes a copy of the page with the skeleton rows removed and measures that too, so you can see the number the skeleton saves:
cd ~/skeleton-demo
cat > check-loading.mjs <<'JS'
import { chromium } from 'playwright';
import assert from 'node:assert/strict';
import { readFile, writeFile, rm } from 'node:fs/promises';
const browser = await chromium.launch();
async function open(file, options = {}) {
const context = await browser.newContext({ viewport: { width: 390, height: 844 }, ...options });
const page = await context.newPage();
// Add up every layout shift from the first paint onwards.
await page.addInitScript(() => {
window.layoutShift = 0;
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (!entry.hadRecentInput) window.layoutShift += entry.value;
}
}).observe({ type: 'layout-shift', buffered: true });
});
await page.goto(new URL(file, import.meta.url).href);
return page;
}
const rowHeights = (page) =>
page.locator('.appt').evaluateAll((rows) => rows.map((r) => r.getBoundingClientRect().height));
const helpTop = (page) => page.locator('.help').evaluate((el) => el.getBoundingClientRect().top);
// 1. While loading: three skeleton rows, shimmering, invisible to screen readers.
const page = await open('index.html?delay=1500');
assert.equal(await page.locator('.appt--skeleton').count(), 3);
assert.equal(await page.getByRole('list').getAttribute('aria-busy'), 'true');
assert.equal(await page.getByRole('listitem').count(), 0, 'skeleton rows are hidden from assistive technology');
assert.equal(await page.getByRole('status').textContent(), 'Loading appointments');
const shimmer = await page.locator('.bone').first().evaluate((el) => getComputedStyle(el, '::after').animationName);
assert.equal(shimmer, 'shimmer');
const skeletonHeights = await rowHeights(page);
const helpBefore = await helpTop(page);
// 2. After loading: real rows, same sizes, nothing moved.
await page.getByRole('status').filter({ hasText: '3 appointments loaded' }).waitFor();
await page.waitForTimeout(500);
assert.equal(await page.getByRole('listitem').count(), 3);
assert.equal(await page.getByRole('list').getAttribute('aria-busy'), 'false');
assert.ok(await page.getByText('Nurse appointment').isVisible());
assert.deepEqual(await rowHeights(page), skeletonHeights, 'loaded rows are the same height as skeleton rows');
assert.equal(await helpTop(page), helpBefore, 'the help line did not move');
const shift = await page.evaluate(() => window.layoutShift);
assert.equal(shift, 0, 'no layout shift');
console.log(`with skeleton: rows ${skeletonHeights.join(', ')} px, layout shift ${shift}`);
// 3. Reduced motion: the bars stay still.
const calm = await open('index.html?hold', { reducedMotion: 'reduce' });
const calmAnimation = await calm.locator('.bone').first().evaluate((el) => getComputedStyle(el, '::after').animationName);
assert.equal(calmAnimation, 'none');
console.log('reduced motion: no shimmer');
// 4. For comparison: the same page with the skeleton rows removed.
const html = await readFile(new URL('index.html', import.meta.url), 'utf8');
const bare = html.replace(/<li class="appt appt--skeleton"[\s\S]*?<\/li>\s*/g, '');
await writeFile(new URL('no-skeleton.html', import.meta.url), bare);
const jumpy = await open('no-skeleton.html?delay=1500');
await jumpy.getByRole('status').filter({ hasText: '3 appointments loaded' }).waitFor();
await jumpy.waitForTimeout(500);
const jumpyShift = await jumpy.evaluate(() => window.layoutShift);
await rm(new URL('no-skeleton.html', import.meta.url));
assert.ok(jumpyShift > 0, 'without a skeleton the help line moves');
console.log(`without skeleton: layout shift ${jumpyShift.toFixed(3)}`);
await browser.close();
console.log('PASS: skeleton matches the loaded layout');
JS
node check-loading.mjsA few details in the script are deliberate:
getByRole('listitem')finds list items the way assistive technology sees them, so it counts zero while the only items are hidden skeleton rows, and three once the real rows are in.addInitScriptstarts the observer before the page's own code runs, andbuffered: truecollects any shift that happened before the observer was created.hadRecentInputexcludes shifts right after a tap or key press, which are expected. Nothing here involves input, so every shift counts.- The phone-sized viewport (390 by 844 pixels) is where most Larkfield patients look at their bookings, and where a wrapped line is most likely.
Check it worked
The output ends with three lines like these, followed by PASS: skeleton matches the loaded layout:
with skeleton: rows 102, 102, 102 px, layout shift 0
reduced motion: no shimmer
without skeleton: layout shift 0.017Each row is 102 pixels: 16 of padding top and bottom, lines of 24, 24 and 20, and a 1-pixel border top and bottom. Because every line height is fixed, that number does not depend on the font. The score without the skeleton varies with the window size, but it is above zero, because the help line moves down when the rows arrive. It is small here only because the help line is the only thing below the list; on a screen with a tab bar, buttons or more content under the list, every one of them would move and the score would grow. With the skeleton it is exactly 0. To see the check catch a real mistake, change height: 0.75em on .bone to height: 2em in style.css and run node check-loading.mjs again: it stops with an AssertionError about the row heights and prints no PASS line. Change it back and it passes again.
To watch shifts while you work on other pages, Chrome and Edge can highlight them on screen: in the Rendering panel from the reduced-motion step, tick "Layout shift regions", and any area that moves flashes blue.
Step 8 · Clean up
Remove the demo folder, which also removes the local Playwright install. The browser Playwright downloaded stays in its shared cache; npx playwright uninstall removes that too if you no longer need it.
cd ~
rm -rf ~/skeleton-demoCheck it worked
ls ~/skeleton-demo reports that there is no such file or directory.
Next steps
- A skeleton is right for content that takes a second or more. Decide what each Larkfield screen should show for shorter and much longer waits, including a "taking longer than usual" state for slow networks, in design loading states: spinners, skeletons and progress.
- Add purposeful motion elsewhere in the app, each with a reduced-motion version, in animate with CSS and respect reduced motion.
- Tell people when loading fails, and how to try again, with announce errors and notices with a live region.
Part of these paths
Related tutorials
- Design loading states: spinners, skeletons and progressYou will have a loading-state table for every wait in a booking flow, with the pattern chosen by expected wait time, and Figma frames for a skeleton, a button spinner, an upload progress bar, an optimistic switch and a "taking longer than usual" state.
- Animate with CSS and respect reduced motionYou will add three purposeful animations to the Larkfield Clinic booking flow with CSS transitions and keyframes, give each one a calmer version for people who ask for less motion, and prove both versions with a browser test.
- Announce errors and notices with a live regionYou will build two Larkfield Clinic banners, a polite "10:30 was just taken" notice and an urgent "could not book" error, that screen readers announce once each, plus a Playwright script that checks them in the accessibility tree.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials