Back to the catalogue Courses

HTML and CSS: build an accessible web page

Structure a semantic page, master the cascade and layouts, make it responsive and verify its basic accessibility.

MDJAD Intermediate 23 min read

Objectives and prerequisites

By the end of this course, you will be able to build a structured web page, style it without blindly copying a mock-up, make it readable on mobile and verify its basic accessibility. The common thread is a project presentation page: navigation, header, content, cards, contact form and footer.

Prerequisites: create a text file and open it in a browser. No prior HTML or CSS knowledge is required. The examples use the HTML Living Standard and modern CSS supported by current browsers. Avoid experimental features until they are necessary.

Path: chapters 1 to 4 cover the document, semantics, media and forms; chapters 5 to 8 cover selectors, the box model, flow and layouts; chapters 9 to 12 cover responsive design, accessibility, developer tools and synthesis. Expect about twenty-five minutes of reading and four to five hours of practice.

Convention: files are index.html and styles.css in a laboratory directory. Open the page with a local server rather than file:// when testing paths or forms. Content is fictional. Each chapter ends with a check you can reproduce.

1. From file to page: browser, request and DOM

When you open an address, the browser sends an HTTP request to the server. The server returns HTML, then the browser downloads linked resources: CSS, images, fonts, JavaScript. It parses the HTML and builds the DOM, a tree representation of the elements. CSS is applied to that tree to produce the visual rendering.

HTML describes meaning and structure: a heading, a paragraph, a navigation, a form. CSS describes presentation: colours, sizes, spacing, layout. Separating the two lets you change appearance without rewriting content, and keeps the document understandable to screen readers, search engines and extraction tools.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Kelia project — presentation</title>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <h1>Kelia project</h1>
    <p>A demonstration project.</p>
  </body>
</html>

The doctype tells the browser to use standards mode. The lang attribute declares the document language, useful for speech synthesis, hyphenation and translation. UTF-8 charset prevents misdisplayed characters. The viewport is essential for the page to adapt to screen width on mobile.

The DOM can be inspected in developer tools. Do not confuse it with the source code: the browser may correct invalid HTML, and JavaScript may modify the DOM after loading. To diagnose, compare what you wrote, what the browser built and what CSS computes.

A page is not only its HTML. Images have weight, fonts can delay text, CSS can block rendering. For a simple page this remains manageable; for a rich page, measure load time and visual shift. Chapter 12 returns to these aspects.

Finally, distinguish visual rendering from information. A page can be beautiful and inaccessible, or austere and perfectly usable. The goal is not to oppose design and accessibility, but to build a page whose structure remains understandable when styles are disabled, the screen is small or the user navigates by keyboard.

Progressive enhancement starts with a working HTML document, then adds CSS and JavaScript as improvements. A page built this way remains usable when a stylesheet fails, when JavaScript is blocked or when a network is slow. This is not nostalgia: it is a robust default. Test the page with CSS disabled and with images blocked to see what information survives. If the content becomes meaningless, the structure is carrying too little meaning.

2. HTML structure and semantics

An HTML document is made of nested elements. Each element has an opening tag, content and a closing tag. Some elements are empty, such as img or meta. Attributes specify behaviour: href for a link, src for an image, alt for alternative text.

Semantics means choosing the element that best describes the content's role. header, nav, main, section, article, aside and footer describe page regions. h1 to h6 describe heading hierarchy. button describes an action; a describes a link to a resource. Using a div for everything deprives the browser and assistive technology of useful information.

<body>
  <a class="skip-link" href="#content">Skip to content</a>
  <header>
    <p class="brand">Kelia</p>
    <nav aria-label="Main navigation">
      <ul>
        <li><a href="#project">The project</a></li>
        <li><a href="#contact">Contact</a></li>
      </ul>
    </nav>
  </header>
  <main id="content">
    <h1>Kelia project</h1>
    <section id="project">
      <h2>A useful project</h2>
      <p>…</p>
    </section>
  </main>
  <footer>…</footer>
</body>

Heading order must be coherent. An h2 must not appear before the h1, and you do not jump from h2 to h4 without reason. Visual hierarchy may differ from semantic hierarchy: an important subheading may be an h2 styled small. Do not choose a heading level for its size; choose it for its place in the outline.

Regions should be unique where relevant: one main per page, one principal header and footer. section elements should have a heading, otherwise they are not identifiable sections. An article should be distributable independently. These rules are not decorative: they help navigation within the document.

The skip link lets keyboard users go directly to content. It must be visible when focused, not only present in the code. Navigation labels must be explicit: "Main navigation" is more useful than "menu". A link must describe its destination; "click here" gives no information out of context.

Finally, validate the HTML. A validator reports improperly nested elements, unknown attributes and structure errors. The browser tolerates a lot, but that tolerance varies. A valid document is more predictable and easier to maintain. Validation does not guarantee accessibility, but it removes a class of errors.

Landmarks make the page navigable by region. A screen-reader user can jump to the main content, navigation, complementary information or footer without reading everything. Use native elements first; add ARIA roles only when no native element expresses the meaning. A div role="navigation" is weaker than a real nav, because it lacks built-in behaviour and is easier to misuse. The first rule of ARIA is not to use ARIA when HTML already does the job.

3. Links, images, paths and formats

A link uses a with an href attribute. The path may be relative or absolute. A relative path depends on the document location; an absolute path starts with / or a scheme. Use relative paths for site resources and full URLs for external destinations. Test from several pages, because a path correct from the home page may be wrong from a subpage.

An image uses img with src and alt. Alternative text describes the information carried by the image, not its appearance. For a decorative image, alt="" is appropriate. For an informative image, describe what it contributes. For a complex image such as a chart, provide a short description and a detailed alternative in the text or a table.

<figure>
  <img src="images/team.webp" alt="Three Kelia team members in front of the office."
       width="800" height="600" loading="lazy">
  <figcaption>The team at the launch workshop.</figcaption>
</figure>

The width and height attributes let the browser reserve space before loading and reduce visual shift. They do not necessarily set the final size: CSS can adapt the image. Lazy loading, loading="lazy", is useful for images below the fold but can delay a visible image if applied everywhere.

The format depends on content. WebP is often a good compromise for photographs; AVIF offers better compression but more recent support; PNG suits images with transparency or sharp screenshots; SVG suits logos and vector illustrations. For photographs, provide several sizes with srcset and sizes so the browser chooses the most suitable.

figure and figcaption connect an image to its explanation. For a clickable logo, the link must have an accessible name: a useful alt or visible text. For an icon alone, add hidden text or a relevant aria-label. Do not repeat in the alt text already present next to the image.

Finally, check image rights and provenance. An image found online is not royalty-free by default. Optimise weight, but do not degrade readability. A heavy image slows the page and consumes mobile data; an over-compressed image may become illegible. Measure and compare.

4. Forms, labels and validation

A form contains fields and a submit button. Each field must have an associated label, either by for and id or by wrapping. The label must describe the expected information. A placeholder does not replace a label: it disappears on input and is not always read correctly by assistive technology.

<form action="/contact" method="post">
  <div class="field">
    <label for="name">Name</label>
    <input id="name" name="name" type="text" autocomplete="name" required>
  </div>
  <div class="field">
    <label for="email">Email address</label>
    <input id="email" name="email" type="email" autocomplete="email" required>
  </div>
  <div class="field">
    <label for="message">Message</label>
    <textarea id="message" name="message" rows="5"></textarea>
  </div>
  <button type="submit">Send</button>
</form>

The field type guides the mobile keyboard and browser validation: email, tel, url, number, date. Choose the type matching the data, without expecting security validation. Browser validation improves experience, but it can be bypassed. The server must always validate and reject incorrect data.

Required fields may use required, but the label must also indicate the requirement, for example "Name (required)". Errors must be associated with the relevant field, with an understandable message and a logical link. Do not settle for a red border: add text and, where possible, aria-describedby to the message.

Group related choices with fieldset and legend, especially for radio buttons and checkboxes. A group of radio buttons without a shared name does not work as a single choice. Checkboxes must have a distinct label. For drop-down lists, the first choice must not be an ambiguous valid option.

The autocomplete attribute helps fill known information: name, address, email, phone. It improves experience and cognitive accessibility. Do not use it for sensitive data or to bypass validation. The button must have an explicit label: "Send message" is clearer than "OK".

Finally, test the form by keyboard and with a screen reader. Check tab order, focus visibility, error messages and behaviour after submission. A form that works with a mouse may be unusable without one. Form accessibility is as much about structure as style.

Error handling must help recovery. Say what is wrong and how to fix it: "Enter an email address in the form name@example.com" is better than "invalid field". Keep the user's input after a failed submission, focus the first error or provide a summary with links, and do not clear the whole form. Announce errors to assistive technology with a live region when the error appears after an asynchronous check, but avoid noisy announcements on every keystroke.

5. Selectors, cascade, inheritance and specificity

A CSS selector targets elements. p targets all paragraphs, .card elements with the class, #contact the element with the identifier, [type="email"] fields of that type. Combinators express a relationship: nav a targets descendant links, > direct children, + the next sibling.

:root {
  --text-color: #1f2933;
  --accent-color: #0b6e4f;
  --space: 1rem;
}

body {
  color: var(--text-color);
  font-family: system-ui, sans-serif;
  line-height: 1.6;
}

.card h2 {
  margin-block: 0 var(--space);
  color: var(--accent-color);
}

The cascade determines which style applies when several rules target the same element. Rule origin, importance, specificity and order matter. A browser rule, an author rule and an !important rule do not carry the same weight. On a tie, the last declared rule wins. Understanding the cascade avoids stacking !important to fix a conflict.

Specificity compares selectors: identifiers weigh more than classes, which weigh more than elements. A selector like #contact .card a is very specific and hard to override. Prefer classes and simple selectors. Low specificity makes CSS more predictable and easier to evolve.

Inheritance concerns certain properties, such as colour and font, which pass to descendants unless overridden. Others, such as margin or border, do not inherit. Use inherit, initial or unset deliberately. CSS variables, defined in :root, support consistency and global changes.

Pseudo-classes describe a state: :hover, :focus-visible, :disabled, :checked, :nth-child(). Pseudo-elements create stylable parts, such as ::before and ::after. Do not remove the focus outline without providing a visible replacement. A missing focus state is an accessibility problem, not an aesthetic detail.

Finally, organise CSS. A single file becomes hard to maintain; commented sections or separate files per component help. Avoid overly deep selectors and generic names such as .red: prefer .alert, which describes the role. CSS maintainability depends as much on structure as syntax.

6. Box model, units and overflow

Each element is a box made of four zones: content, padding, border and margin. By default, width refers to content width, and padding and border add to it. With box-sizing: border-box, width includes padding and border, simplifying calculations. Most modern stylesheets apply this rule globally.

*,
*::before,
*::after {
  box-sizing: border-box;
}

.card {
  inline-size: min(100%, 28rem);
  padding: 1.5rem;
  border: 1px solid #d9e2ec;
  border-radius: 0.75rem;
  margin-inline: auto;
}

Absolute units such as px are predictable but do not adapt to user preferences. Relative units such as rem, em, %, vh and vw adapt to context. rem relates to root font size; em to the element's font size. For spacing and typography, prefer rem and consistent values.

An element's width may be constrained by its parent, content or properties. max-width limits width without preventing reduction. min-width does the opposite. For an image, max-width: 100% and height: auto prevent overflow while preserving proportions. For long text, overflow-wrap: anywhere can prevent overflow, but does not replace an adapted width.

Overflow occurs when content is larger than its box. overflow: hidden hides it, auto adds a scrollbar when needed, visible lets it protrude. Hiding overflow can hide essential information or focus. Prefer a layout that adapts, and use auto for areas that must scroll.

Margins can collapse vertically between adjacent elements, which surprises. The phenomenon depends on context; modern layouts such as Flexbox and Grid handle it differently. Use gap to space elements in a flex or grid container, rather than individual margins that are hard to control.

Finally, test with enlarged text and a narrow window. A box that looks correct with short content may overflow with a long title or a longer translation. German or Swahili can produce words longer than English. Allow flexibility rather than fixed widths everywhere.

A spacing scale keeps a page coherent. Define a few values, such as 0.25rem, 0.5rem, 1rem, 1.5rem and 2rem, and use them for margins, padding and gaps. Ad hoc values create visual noise and make responsive adjustments harder. A spacing scale also helps handover: another developer can reuse the same rhythm instead of inventing new numbers. Fewer values, applied consistently, usually look better than many arbitrary ones.

7. Normal flow, display and positioning

In normal flow, block elements take the available width and stack vertically; inline elements flow within text. Understanding this default behaviour avoids moving elements without reason. Before using position, ask whether normal flow or a flex/grid layout is enough.

The display property changes behaviour: block, inline, inline-block, flex, grid, none. display: none removes the element from the rendering tree and tab order; visibility: hidden hides it but keeps its place. For content visually hidden but available to screen readers, use an appropriate visually-hidden class, not display: none.

.site-header {
  position: sticky;
  top: 0;
  z-index: 10;
  background: #fff;
}

.alert {
  position: relative;
  padding-inline-start: 2.5rem;
}

.alert::before {
  content: "!";
  position: absolute;
  inset-inline-start: 1rem;
  inset-block-start: 1rem;
}

position: static is the default. relative offsets the element from its normal position and often serves as a reference for an absolute child. absolute removes the element from flow and positions it relative to its positioned ancestor. fixed positions it relative to the viewport. sticky combines flow and an offset during scrolling.

Absolute positioning reserves no space, which can cause overlaps. Use it for decorative elements or tooltips, not main structure. z-index only works on positioned elements or in certain flex/grid contexts; stacking high z-index values is often a sign of confused structure.

Modern layouts reduce the need for positioning. Flexbox handles a row or column; Grid handles two dimensions. For a navigation bar, Flexbox is often enough. For a card gallery, Grid is more natural. The next chapter compares the two.

Finally, check reading order. Visual positioning must not contradict DOM order. A keyboard user or screen reader follows code order, not CSS movement. If you visually reorder elements, ensure the logical order remains coherent, or fix the HTML.

8. Flexbox and Grid

Flexbox organises elements on a main axis, horizontal or vertical. display: flex creates a flex container; flex-direction chooses the axis; justify-content distributes on the main axis; align-items aligns on the cross axis; gap spaces elements. Children can grow or shrink with flex-grow, flex-shrink and flex-basis.

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min(100%, 16rem), 1fr));
  gap: 1.5rem;
}

.bar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: 1rem;
}

Grid organises elements on two dimensions. grid-template-columns defines columns, grid-template-rows rows, gap spacing. repeat(auto-fit, minmax(...)) creates a responsive grid without a media query: columns shrink and wrap when space runs out. auto-fill and auto-fit behave differently when there are few elements.

Choose Flexbox for one-axis distribution, a toolbar, a button group or a card with content and footer aligned. Choose Grid for a row-and-column composition, a gallery, a dashboard or a page with named areas. The two can combine: a grid of cards where each card uses Flexbox internally.

Placement may be automatic or explicit. grid-column and grid-row place an element on precise lines. Named lines and grid-template-areas make complex compositions more readable. Pay attention to reading order and responsive behaviour: an area moved visually must remain logical in the DOM.

Test with few and many elements. A grid that works with six cards may behave differently with one, or with very long text. Check wrapping, alignment and spacing. minmax(0, 1fr) sometimes prevents overflow caused by an overly wide minimum content size.

Finally, do not use Flexbox or Grid to fix badly structured HTML. These tools organise elements; they do not replace a correct semantic hierarchy. A beautiful grid of divs without headings or accessible links remains a page that is hard to use. Structure comes first, layout second.

Container queries extend the responsive idea: a component can adapt to the width of its container rather than the viewport. This is useful for cards placed in different columns, because the same card can be narrow in a sidebar and wide in a main area. Support is recent but broad; provide a sensible fallback. Do not replace media queries everywhere: viewport-based rules remain appropriate for page-level layout.

9. Responsive: mobile first, fluid widths and images

A responsive page adapts to screen width and user preferences. The mobile-first approach writes styles for a small screen, then adds rules for larger screens with min-width. This avoids overloading mobile with desktop styles to undo.

.container {
  inline-size: min(100% - 2rem, 72rem);
  margin-inline: auto;
}

@media (min-width: 48rem) {
  .card-grid {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

@media (min-width: 64rem) {
  .card-grid {
    grid-template-columns: repeat(3, minmax(0, 1fr));
  }
}

Breakpoints must be chosen from content, not specific devices. A layout that breaks at 37rem should be fixed around that width. Media queries can also target preferences: prefers-reduced-motion, prefers-color-scheme, prefers-contrast. Respect these preferences rather than ignoring them.

Fluid widths use %, min(), max() and clamp(). clamp(1rem, 2.5vw, 2rem) bounds a size between a minimum and a maximum. Viewport units alone can cause problems with mobile navigation bars; prefer combinations with rem or dvh when necessary.

Images must adapt without distortion: max-width: 100%, height: auto, and width/height attributes. For content images, srcset and sizes choose an adapted resolution. Do not load a 3000 px image for a 300 px thumbnail. Saved weight improves loading and energy use.

Text zoom must remain possible. Do not disable zoom with user-scalable=no. Test at 200% zoom: content must not be truncated or overlap. A layout that requires horizontal zoom to read is an accessibility problem. Grids and fluid widths help avoid this.

Finally, test at real widths, not only in browser resizing. Devices have different densities and fonts. Also check landscape mode, long text and translations. A responsive page is not a page that "fits" a phone: it is a page that remains readable and usable under varied conditions.

10. Typography, contrast, focus and keyboard

Typography influences readability. A body size of at least 1rem, line height around 1.5 to 1.7 and a line width of 45 to 75 characters are useful references. Avoid justified paragraphs without hyphenation, long uppercase text and decorative fonts for body copy. Readability comes before visual effect.

Contrast between text and background must be sufficient. WCAG recommends at least 4.5:1 for normal text and 3:1 for large text. Light grey on white may look elegant but be illegible. Use a contrast checker and test hover, focus and disabled states, not only the normal state.

:focus-visible {
  outline: 3px solid #0b6e4f;
  outline-offset: 3px;
}

.btn {
  display: inline-flex;
  align-items: center;
  min-block-size: 2.75rem;
  padding-inline: 1.25rem;
  border: 2px solid transparent;
  border-radius: 0.5rem;
  background: #0b6e4f;
  color: #fff;
  text-decoration: none;
}

.btn:hover {
  background: #095c42;
}

Keyboard focus must be visible on all interactive elements: links, buttons, fields, scrollable areas. Do not remove outline without replacement. :focus-visible distinguishes keyboard focus from mouse click, but the style must remain perceptible. A thin or low-contrast outline is not enough.

Keyboard navigation must follow logical document order. Tab moves forward, Shift+Tab backward, Enter activates a link or button, Space activates a button or checkbox. Drop-down menus must open and close by keyboard, and focus must not be trapped without an exit. Test without a mouse.

Colour must not be the only way to convey information. A red error message must also have text and an icon or label. A link in a paragraph must be distinguished by more than colour, for example by underlining. Colour-blind or low-vision users must not lose information.

Finally, respect motion preferences. A looping animation or automatic scrolling can disturb. @media (prefers-reduced-motion: reduce) reduces or removes non-essential animations. Accessibility is not a checkbox: it is a set of decisions that make the page usable by more people.

Motion preferences apply to transitions, parallax, carousels and animated illustrations. Provide a reduced version rather than removing all feedback, because a state change without any visual cue can confuse. Also avoid autoplay with sound and respect the user's pause control. An animation that cannot be paused or stopped may violate accessibility guidelines, even if it looks harmless to the author.

11. Developer tools and diagnosis

Browser developer tools let you inspect the DOM, computed styles, each element's box, the network and the console. The inspector shows the cascade and applied rules, including struck-through ones. It is the starting point for understanding why a style does not apply.

Diagnosing a broken layout
1. Does the element exist in the DOM?
2. Is the CSS rule loaded, and does the selector match?
3. Is the property overridden by a more specific rule?
4. Does the box have an unexpected width, padding or border?
5. Does the parent limit width or overflow?
6. Does behaviour change at another width?

The "Computed" tab shows final values. The "Layout" tab highlights grids and flexboxes. Responsive mode simulates widths and densities. The network tab shows missing or heavy resources. The console reports JavaScript errors and sometimes CSS loading errors.

To diagnose overflow, temporarily outline every element: * { outline: 1px solid red; }. This reveals boxes that protrude. Remove the style afterwards. To understand a grid, inspect lines and areas. For a focus problem, navigate by keyboard and observe the active element.

Do not change CSS only in the tools without reporting the fix to the file. Inspector changes are temporary and disappear on reload. Use them to test a hypothesis, then apply the correction in the source and reload. Diagnosis without a reproducible fix is not finished.

Also validate HTML and CSS with dedicated tools. An HTML validator reports structure errors; a CSS analyser reports unknown properties. Automated accessibility tests detect some problems but do not replace manual keyboard and screen-reader testing. Tools find symptoms, not the whole user experience.

Finally, document recurring problems and solutions. A team that knows why a container uses minmax(0, 1fr) avoids repeating the mistake. Diagnosis is a shareable skill: a short comment or a documentation note is better than an unexplained fix.

Keep a manual test checklist for each page: keyboard-only journey, visible focus, 200% zoom, narrow viewport, high contrast, reduced motion, images with alt text and a form submitted with errors. Automated tools catch only part of this. Run the checklist before delivery and record the browser and date. A page that passes a scanner but traps keyboard focus is still not accessible, and a checklist that is never updated becomes a ritual rather than a safeguard, so review it after each accessibility finding and after every significant change to the page structure, and keep the results with the page so future changes can be compared and regressions spotted early. This habit turns accessibility from a one-off audit into a durable team practice for everyone involved today on the web.

12. Synthesis: assemble, test and improve

The presentation page brings the elements together: a header with navigation, a main content area with a heading and sections, a card grid, a contact form and a footer. Each part has a semantic structure, responsive style and accessible behaviour. The whole must remain readable without CSS, by keyboard and on a narrow screen.

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min(100%, 16rem), 1fr));
  gap: 1.5rem;
}

.card {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  padding: 1.5rem;
  border: 1px solid #d9e2ec;
  border-radius: 0.75rem;
}

.card a {
  margin-block-start: auto;
}

Test in this order: valid HTML structure, keyboard navigation, 200% zoom, mobile width, contrast, images and form. Fix structure first, because CSS cannot compensate for bad HTML. Then adjust layout and typography. Finally, check interactive states and motion preferences.

Justify your choices: why a section rather than a div, why Flexbox for the bar and Grid for cards, why a rem unit, why a given contrast. An unjustified choice is hard to maintain. An accessible page is not one that ticks boxes: it is one whose decisions are understandable.

To go further, explore reusable components, CSS variables, light and dark themes, respectful animations and automated accessibility tests. But do not complicate before you have a simple, correct and tested page. Interface quality is measured by its ability to serve real users under real conditions.

Finally, keep the page maintainable. Role-describing classes, organised files, useful comments and short documentation help the next person. HTML and CSS evolve; a semantic base and predictable styles make changes less risky. The best optimisation is often a clear structure.

Performance is part of accessibility. Large images, render-blocking stylesheets, unused fonts and excessive scripts delay the content, especially on slow connections. Compress images, subset fonts, defer non-critical scripts and avoid layout shifts by reserving space. Measure with browser tools and throttled networks, not only on a fast office connection. A page that loads quickly is usable by more people and consumes less energy.

Exercise 1 — Semantic structure

Write the structure of a project page with a header, navigation, main content, two sections, a three-card grid and a footer. Add a skip link and verify heading hierarchy.

Solution

Use header, nav with an aria-label, main, section with h2 headings and footer. The h1 is unique and precedes the h2s. The skip link points to #content and becomes visible on focus. Cards may be article if they make sense independently, or div if purely decorative. The structure must remain understandable without CSS.

Exercise 2 — Images and alternatives

Add a team image, a clickable logo and a search icon alone. Write alternative texts and explain the choice for each image. What should be done for a purely decorative image?

Solution

The team image has a descriptive alt. The clickable logo has an accessible name, for example alt="Kelia — home". The icon alone has hidden text or an aria-label "Search". A decorative image uses alt="" to be ignored by screen readers. Alternative text describes information, not colour or style.

Exercise 3 — Accessible form

Build a contact form with name, email, subject and message. Associate each label, mark required fields, add an error message for email and verify tab order.

Solution

Each field has an id and a label for. Required fields use required and the label says so. The error message is visible text linked by aria-describedby. The button has an explicit label. Tab order follows DOM order. Server validation remains necessary because browser validation can be bypassed.

Exercise 4 — Cascade and specificity

Two rules target the same heading: #contact h2 and .card h2. Which wins and why? Propose a less specific, more maintainable organisation.

Solution

#contact h2 is more specific because of the identifier and wins. To avoid conflicts, use classes such as .card__title and avoid identifiers in style selectors. Low specificity makes overrides predictable. Keep identifiers for anchors and ARIA relationships, not styling.

Exercise 5 — Box model and layout

A card overflows its container. Diagnose three possible causes and propose a fix for each. Explain the effect of box-sizing: border-box.

Solution

Causes: a fixed width larger than the parent, padding and border added to width, or unbreakable content wider than the box. Fixes: use max-width: 100%, apply box-sizing: border-box, allow wrapping with overflow-wrap or reduce size. border-box includes padding and border in the declared width, preventing unintended overflow.

Exercise 6 — Responsive and accessibility

Turn a fixed three-column grid into a responsive grid, then check 200% zoom, keyboard focus and contrast. Describe the tests performed and the fixes.

Solution

Use grid-template-columns: repeat(auto-fit, minmax(min(100%, 16rem), 1fr)) and a gap. At 200%, the grid should become one column without overflow. Focus must remain visible on links and buttons. Text and state contrast must reach 4.5:1. Record tested widths, browser and results. A screenshot or dated note is evidence.

Capstone — complete project page

Deliver a project presentation page with navigation, hero, sections, card grid, form and footer. HTML must be valid and semantic; CSS must use variables, a consistent box model, Flexbox or Grid as appropriate, and a mobile-first approach. The page must be usable by keyboard, at 200% zoom and with sufficient contrast.

Grid: valid structure; coherent heading hierarchy; images with alternatives; form with labels and errors; visible focus; verified contrast; responsive without overflow; organised and commented code. Record tests, widths, browser and limits. A page that works only on your screen is not delivered.

Common errors and diagnostic method

Using div everywhere, skipping heading levels, removing focus, using a placeholder instead of a label, forgetting alt, fixing widths in pixels everywhere, stacking !important and believing browser validation is enough are classic errors. A page can look correct and be inaccessible.

Method: validate HTML, inspect the DOM and computed styles, test by keyboard, reduce width, zoom, check contrast, then fix the cause. Compare expected and observed state. Document the fix and the test. A layout problem is often diagnosed by walking from the symptom back to the rule that applies it.

Self-assessment

You should now be able to explain the difference between HTML and CSS, choose a semantic element, associate a label with a field, explain cascade and specificity, calculate a width with the box model, choose Flexbox or Grid, write a mobile-first media query, check contrast and focus.

Self-assessment: I can structure a page without unnecessary divs; I can write a relevant alt; I can diagnose overflow; I can make a grid responsive; I can navigate by keyboard; I can justify layout choices. To progress, study design systems, accessibility testing and web performance.

References