Fifteen spreads in three parts: HTML for structure, CSS for style, JavaScript for behavior. Each has a picture, the idea, and code you can paste into a file and open in a browser.
"Semantic, accessible HTML first; a mobile-first CSS layout with grid, flexbox and custom properties; then progressive enhancement with vanilla JS: event delegation, async/await fetches, and state in localStorage."
Every phrase in that sentence gets its own page. Use the tabs or the ← → keys.
The browser looks up the domain (DNS), sends an HTTP request, gets back HTML, then fetches every CSS, JS and image file the HTML mentions. The browser turns all of it into pixels.
index.html, style.css, app.js.index.html → Open with Live Server.F12 for DevTools: Elements, Console, Network.$ mkdir my-site && cd my-site $ python -m http.server 8000 # → http://localhost:8000 $ npx serve . # if you have Node
https://shop.com:443/cart?id=7#top → scheme · host · port · path · query · fragmentHTML is made of elements: an opening tag, optional attributes, content, and a closing tag. Elements nest inside each other, and the browser builds them into a tree called the DOM.
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>My First Site</title> <link rel="stylesheet" href="style.css"> <script src="app.js" defer></script> </head> <body> <h1>Hello, web!</h1> <p>This is <strong>important</strong> and <em>stressed</em>.</p> <ul> <li>HTML</li> <li>CSS</li> </ul> <!-- comments look like this --> </body> </html>
<div> <p> <h1> start new lines · <span> <a> <strong> flow in textSemantic elements describe meaning. Screen readers use them to jump between regions, search engines use them to understand content, and you'll thank yourself when reading the code later.
<header> <a href="/" class="logo">Ada's Blog</a> <nav aria-label="Main"> <ul> <li><a href="/" aria-current="page">Home</a></li> <li><a href="/about">About</a></li> </ul> </nav> </header> <main> <article> <h1>Why Semantics Matter</h1> <p>Posted <time datetime="2026-10-29">Oct 29</time></p> <h2>The short version</h2> <blockquote>Use the right tag for the job.</blockquote> </article> <aside>Related posts…</aside> </main> <footer>© 2026 Ada</footer>
The <a> tag links anywhere with href. Images need alt text that describes them (or alt="" if they're decoration). Give images width and height so the page doesn't jump while they load.
<a href="about.html">About</a> <a href="https://mdn.dev" target="_blank" rel="noopener">MDN</a> <a href="#contact">Jump to contact</a> <a href="mailto:hi@ada.dev">Email me</a> <img src="img/cat.jpg" alt="Orange cat asleep on a laptop" width="800" height="600" loading="lazy"> <picture> <source srcset="hero.avif" type="image/avif"> <img src="hero.jpg" alt="Mountain at sunrise" srcset="hero-400.jpg 400w, hero-1600.jpg 1600w" sizes="(max-width: 600px) 100vw, 50vw"> </picture> <figure> <video src="demo.mp4" controls muted playsinline></video> <figcaption>A 10-second demo</figcaption> </figure>
Forms gather data. Pick the right type and phones show the right keyboard, and the browser validates it for free. Tie every input to a <label>: it's the single biggest accessibility win.
<form action="/signup" method="post"> <label for="name">Name</label> <input id="name" name="name" required autocomplete="name"> <label for="email">Email</label> <input id="email" name="email" type="email" required> <label for="age">Age</label> <input id="age" name="age" type="number" min="13" max="120"> <label for="plan">Plan</label> <select id="plan" name="plan"> <option>Free</option><option>Pro</option> </select> <fieldset> <legend>Contact me by</legend> <label><input type="radio" name="via" value="email" checked> Email</label> <label><input type="radio" name="via" value="sms"> SMS</label> </fieldset> <button type="submit">Create account</button> </form>
<button> for actions, <a> for navigation, never a clickable <div>"Unplug your mouse and Tab through the page. If you can't do everything with a keyboard, it's not done."
A CSS rule is a selector plus declarations. When several rules hit the same element, the cascade picks one: importance, then specificity, then source order. Keep specificity low and flat (mostly single classes) and you'll rarely fight it.
/* element · class · id · attribute */ p { line-height: 1.6; } .card { border: 1px solid #ccc; } #hero { min-height: 60vh; } a[href^="http"] { text-decoration: underline dotted; } /* combinators */ .card h2 { margin: 0; } /* any h2 inside .card */ .nav > li { display: inline; } /* direct children only */ h2 + p { font-size: 1.1rem; } /* p right after h2 */ /* states and positions */ a:hover, a:focus-visible { color: crimson; } li:nth-child(odd) { background: #f6f6f6; } input:invalid { border-color: red; } .card:has(img) { padding: 0; } /* parent selector! */ .btn::after { content: " →"; } /* group, then reset sanely */ *, *::before, *::after { box-sizing: border-box; } img { max-width: 100%; display: block; }
:hover :focus :checked :first-child::before ::after ::placeholder ::first-line.card__title--big keeps classes flat and clearEvery element is a rectangle. Padding is space inside the border, margin is space outside it. Set box-sizing: border-box everywhere so width means what you think it means.
*, *::before, *::after { box-sizing: border-box; }
.card {
width: min(100%, 40rem); /* fluid, but capped */
padding: 1.5rem; /* all four sides */
padding-inline: 2rem; /* left + right */
margin: 2rem auto; /* auto = center it */
border: 2px solid #152430;
border-radius: 12px;
box-shadow: 0 4px 12px rgb(0 0 0 / .1);
}
.stack > * + * { margin-block-start: 1rem; } /* space between kids */
.title {
font-size: clamp(1.5rem, 4vw, 3rem); /* min, ideal, max */
}
.hidden-but-readable {
position: absolute; width: 1px; height: 1px;
overflow: hidden; clip-path: inset(50%);
}| Unit | Relative to | Use for |
|---|---|---|
| px | nothing (fixed) | borders, shadows |
| rem | root font size | font sizes, spacing |
| em | this element's font | padding on buttons |
| % | parent size | widths |
| vw / vh / dvh | the viewport | full-screen sections |
| ch | width of "0" | readable lines: max-width: 65ch |
Flexbox is for one-dimensional layouts: a row of buttons, a nav bar, a card's header. Put display: flex on the parent; the children become flex items.
/* nav bar: logo left, links right, vertically centered */ .site-header { display: flex; justify-content: space-between; align-items: center; gap: 1rem; } /* perfectly center anything */ .center { display: flex; place-content: center; /* or justify + align: center */ min-height: 100dvh; } /* input that grows, button that doesn't */ .search { display: flex; gap: .5rem; } .search input { flex: 1; } /* grow into spare space */ .search button{ flex-shrink: 0; } /* wrap onto new lines on small screens */ .tags { display: flex; flex-wrap: wrap; gap: .5rem; } /* a column, with the footer pushed to the bottom */ .card { display: flex; flex-direction: column; } .card .footer { margin-top: auto; }
CSS Grid is two-dimensional. Define columns and rows on the parent, then place children by line number or by named area. The fr unit means "a fraction of the leftover space".
.page {
display: grid;
grid-template-columns: 200px 1fr;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
gap: 1rem;
min-height: 100dvh;
}
.page > header { grid-area: header; }
.page > aside { grid-area: sidebar; }
.page > main { grid-area: main; }
.page > footer { grid-area: footer; }
/* the famous responsive card grid, zero media queries */
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 1.5rem;
}
/* make one card span two columns */
.cards .featured { grid-column: span 2; }
/* line numbers: from line 1 to the last line */
.banner { grid-column: 1 / -1; }1fr 2fr → the second column gets twice the spare space"Grid for the page, flex for the components inside it."
Write the phone layout first, then use media queries to add columns on wider screens. Store colors and spacing in custom properties (CSS variables) so a theme switch is just new values.
:root {
--bg: #ffffff;
--text: #152430;
--brand: #2F5BEA;
--space: 1rem;
--radius: 10px;
}
@media (prefers-color-scheme: dark) {
:root { --bg: #0F161C; --text: #E6EDF1; --brand: #6E8FFF; }
}
body { background: var(--bg); color: var(--text); }
.btn { background: var(--brand); padding: var(--space);
border-radius: var(--radius); }
.btn:hover { background: color-mix(in oklch, var(--brand), black 15%); }
/* mobile first: one column by default */
.products { display: grid; gap: var(--space); }
@media (min-width: 600px) { .products { grid-template-columns: 1fr 1fr; } }
@media (min-width: 1000px) { .products { grid-template-columns: repeat(3, 1fr); } }
/* respond to the container, not the screen */
.card-wrap { container-type: inline-size; }
@container (min-width: 400px) { .card { display: flex; } }
@media (prefers-reduced-motion: reduce) {
* { animation: none !important; transition: none !important; }
}transition: transform .2s ease; animates any change smoothlyCtrl+Shift+M) to try phone sizesconst, use let when it must change, forget var.JavaScript runs in every browser. Open DevTools → Console and type along. Use const by default, let if you'll reassign. Always use === (strict equality), which never converts types behind your back.
const name = "Ada";
let score = 0;
score += 10;
console.log(`Hi ${name}, score: ${score}`); // template literal
Hi Ada, score: 10
console.log(typeof 42, typeof "42", typeof null);
number string object // null is a famous bug
console.log(1 == "1", 1 === "1");
true false // == converts, === doesn't
function greet(who = "friend") {
return `Hello, ${who}!`;
}
const shout = (text) => text.toUpperCase() + "!";
console.log(greet(), shout("hey"));
Hello, friend! HEY!
const age = 20;
const label = age >= 18 ? "adult" : "minor"; // ternary
for (let i = 0; i < 3; i++) console.log(i);
const user = null;
console.log(user?.name ?? "guest"); // optional chaining + nullish
guestfalse 0 "" null undefined NaN; everything else is truthynull/undefined; || also replaces 0 and ""An array is an ordered list, an object is a set of named properties. Modern JS chains array methods instead of writing loops, and uses spread to make copies instead of changing data in place.
const products = [
{ name: "Lamp", price: 5, inStock: true },
{ name: "Chair", price: 9, inStock: false },
{ name: "Mug", price: 3, inStock: true },
];
const total = products
.filter(p => p.inStock)
.map(p => p.price)
.reduce((sum, n) => sum + n, 0);
console.log(total);
8
const mug = products.find(p => p.name === "Mug");
const anyCheap = products.some(p => p.price < 4);
const byPrice = products.toSorted((a, b) => a.price - b.price);
const { name, price = 0 } = mug; // destructuring
const [first, ...rest] = products;
const discounted = { ...mug, price: 2 }; // copy + change
const more = [...products, { name: "Pen", price: 1 }];
for (const [key, value] of Object.entries(mug)) {
console.log(key, value);
}
const json = JSON.stringify(mug); // object → text
const back = JSON.parse(json); // text → objectfor…in loops over keys (avoid on arrays)const b = a shares one array; [...a] or structuredClone(a) copiesnew Map() for any-key lookups, new Set(arr) to dedupeThe DOM is the live tree of your HTML that JS can read and change. Grab elements with querySelector, react to events with addEventListener, and change content, classes and attributes.
const form = document.querySelector("#add-form");
const input = document.querySelector("#new-todo");
const list = document.querySelector("#todos");
const items = document.querySelectorAll(".todo"); // all matches
form.addEventListener("submit", (event) => {
event.preventDefault(); // stop the page reload
const text = input.value.trim();
if (!text) return;
const li = document.createElement("li");
li.className = "todo";
li.textContent = text; // safe: no HTML parsed
const del = document.createElement("button");
del.textContent = "✕";
del.setAttribute("aria-label", `Delete ${text}`);
li.append(del);
list.append(li);
input.value = "";
input.focus();
});
// event delegation: one listener for every current AND future button
list.addEventListener("click", (event) => {
const btn = event.target.closest("button");
if (btn) btn.parentElement.remove();
});
list.addEventListener("dblclick", (e) => {
e.target.closest("li")?.classList.toggle("done");
});
document.body.dataset.theme = "dark"; // sets data-theme="dark"click input change submit keydown scroll DOMContentLoaded.add .remove .toggle .contains; let CSS do the stylinginnerHTML = userText lets attackers inject scripts; use textContentNetwork requests take time. JS doesn't stop and wait; fetch returns a Promise right away. Inside an async function, await pauses just that function until the result is ready. Wrap it in try/catch for failures.
async function loadUsers() {
const status = document.querySelector("#status");
status.textContent = "Loading…";
try {
const res = await fetch("https://jsonplaceholder.typicode.com/users");
if (!res.ok) throw new Error(`HTTP ${res.status}`); // fetch won't throw on 404
const users = await res.json();
renderUsers(users);
status.textContent = `${users.length} users`;
} catch (err) {
status.textContent = "Couldn't load users.";
console.error(err);
}
}
function renderUsers(users) {
const ul = document.querySelector("#users");
ul.replaceChildren(...users.map(u => {
const li = document.createElement("li");
li.textContent = `${u.name} · ${u.email}`;
return li;
}));
}
// send data
await fetch("/api/todos", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text: "Learn fetch" }),
});
// run several at once, wait for all
const [posts, users] = await Promise.all([
fetch("/api/posts").then(r => r.json()),
fetch("/api/users").then(r => r.json()),
]);
setTimeout(() => console.log("1s later"), 1000);
loadUsers();.done state (6–10).localStorage on every change, load on start.<main class="card"> <h1>My Tasks</h1> <form id="add"> <label for="text" class="sr-only">New task</label> <input id="text" placeholder="What needs doing?" required> <button>Add</button> </form> <ul id="list"></ul> <p id="count" aria-live="polite"></p> </main>
:root { --brand: #2F5BEA; --bg: #EAF0F2; --card: #fff; }
body { background: var(--bg); font-family: system-ui; display: grid;
place-items: start center; padding: 2rem 1rem; }
.card { background: var(--card); width: min(100%, 28rem); padding: 1.5rem;
border-radius: 12px; box-shadow: 0 6px 20px rgb(0 0 0 / .08); }
form { display: flex; gap: .5rem; } form input { flex: 1; }
li { display: flex; align-items: center; gap: .5rem; padding: .5rem 0; }
li.done span { text-decoration: line-through; opacity: .5; }
li button { margin-left: auto; }
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }const KEY = "todos";
let todos = load();
function load() {
try { return JSON.parse(localStorage.getItem(KEY)) ?? []; }
catch { return []; }
}
function save() { localStorage.setItem(KEY, JSON.stringify(todos)); }
function render() {
const list = document.querySelector("#list");
list.replaceChildren(...todos.map(t => {
const li = document.createElement("li");
li.dataset.id = t.id;
li.classList.toggle("done", t.done);
const box = Object.assign(document.createElement("input"),
{ type: "checkbox", checked: t.done });
const span = Object.assign(document.createElement("span"), { textContent: t.text });
const del = Object.assign(document.createElement("button"), { textContent: "✕" });
del.setAttribute("aria-label", `Delete ${t.text}`);
li.append(box, span, del);
return li;
}));
const left = todos.filter(t => !t.done).length;
document.querySelector("#count").textContent = `${left} left`;
}
function update(next) { todos = next; save(); render(); }
document.querySelector("#add").addEventListener("submit", e => {
e.preventDefault();
const input = e.target.querySelector("input");
update([...todos, { id: crypto.randomUUID(), text: input.value.trim(), done: false }]);
input.value = "";
});
document.querySelector("#list").addEventListener("click", e => {
const id = e.target.closest("li")?.dataset.id;
if (!id) return;
if (e.target.matches("button")) update(todos.filter(t => t.id !== id));
if (e.target.matches("input")) update(todos.map(t =>
t.id === id ? { ...t, done: !t.done } : t));
});
render();"HTML says what things are, CSS says how they look on every screen, and JavaScript keeps the data, listens for events, and re-renders the DOM from that data."