
Designing Beautiful Websites
- 2.2k installs
- 3 repo stars
- Updated June 29, 2026
- tristanmanchester/agent-skills
designing-beautiful-websites is an agent skill that >-.
About
Core philosophy Make the next action obvious Build from user goals upward Systemise visuals Validate early Why this exists Websites fail when they look nice but don t match user goals hide key actions require too much thinking or are visually inconsistent This skill turns vague requests like make it look better into a repeatable workflow that produces clear structure usable interactions and a cohesive visual system What done looks like Deliverables should be usable by builders engineers no code builders future agents Design brief users goals constraints success metrics IA flows sitemap or nav model and 1 3 key user journeys Layout wireframes responsive page structure component inventory Visual system tokens type spacing colour radius shadow and usage rules Component specs states behaviour empty loading error QA notes accessibility responsiveness edge cases If time is limited prioritise clarity hierarchy consistency accessibility
- Designs UX/UI for websites and web apps: UX strategy, information architecture,
- user flows, wireframes, UI systems, component specs, and polished visual design.
- Use when the user asks to design, redesign, modernise, critique, or improve a
- Follow designing-beautiful-websites SKILL.md steps and documented constraints.
- Follow designing-beautiful-websites SKILL.md steps and documented constraints.
Designing Beautiful Websites by the numbers
- 2,202 all-time installs (skills.sh)
- +80 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #525 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
designing-beautiful-websites capabilities & compatibility
- Capabilities
- designs ux/ui for websites and web apps: ux stra · user flows, wireframes, ui systems, component sp · use when the user asks to design, redesign, mode · follow designing beautiful websites skill.md ste
- Use cases
- orchestration
What designing-beautiful-websites says it does
Designs UX/UI for websites and web apps: UX strategy, information architecture,
user flows, wireframes, UI systems, component specs, and polished visual design.
Use when the user asks to design, redesign, modernise, critique, or improve a
npx skills add https://github.com/tristanmanchester/agent-skills --skill designing-beautiful-websitesAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 2.2k |
|---|---|
| repo stars | ★ 3 |
| Security audit | 3 / 3 scanners passed |
| Last updated | June 29, 2026 |
| Repository | tristanmanchester/agent-skills ↗ |
When should an agent use designing-beautiful-websites and what problem does it solve?
>-
Who is it for?
Developers invoking designing-beautiful-websites as documented in the skill source.
Skip if: Skip when requirements fall outside designing-beautiful-websites documented scope.
When should I use this skill?
>-
What you get
Outputs aligned with the designing-beautiful-websites SKILL.md workflow and stated deliverables.
- wireframes
- UI system spec
- UX strategy document
Files
Designing Beautiful Websites
Core philosophy: Make the next action obvious. Build from user goals upward. Systemise visuals. Validate early.
Why this exists
Websites fail when they look “nice” but:
- don’t match user goals,
- hide key actions,
- require too much thinking,
- or are visually inconsistent.
This skill turns vague requests like “make it look better” into a repeatable workflow that produces:
- clear structure,
- usable interactions,
- and a cohesive visual system.
What “done” looks like
Deliverables should be usable by builders (engineers, no-code builders, future agents):
- Design brief: users, goals, constraints, success metrics.
- IA + flows: sitemap (or nav model), and 1–3 key user journeys.
- Layout + wireframes: responsive page structure, component inventory.
- Visual system: tokens (type, spacing, colour, radius, shadow), and usage rules.
- Component specs: states, behaviour, empty/loading/error.
- QA notes: accessibility, responsiveness, edge cases.
If time is limited, prioritise: clarity + hierarchy + consistency + accessibility.
Quick start workflow
Copy this checklist into the working notes and tick it off:
- [ ] 0. Inputs: goal, audience, content, constraints, brand signals.
- [ ] 1. Strategy: user goals + business goals + success metrics.
- [ ] 2. Scope: pages/features/content; prioritise “key paths”.
- [ ] 3. Structure: IA + navigation model + flows.
- [ ] 4. Skeleton: wireframes + component inventory + responsive layout.
- [ ] 5. Surface: visual system + page comps + states.
- [ ] 6. Validate: usability pass + accessibility pass + consistency pass.
- [ ] 7. Hand-off: tokens + component specs + implementation notes.
Default rule: do not jump to surface polish until structure and skeleton are believable.
Non‑negotiables
1) Reduce thinking
Design so users rarely wonder:
- “Where am I?”
- “What do I do next?”
- “Is that clickable?”
- “Why did they call it that?”
Prefer obvious over clever.
2) Use conventions aggressively
Use familiar patterns unless there is a measured reason to deviate. Unusual UI is a tax on every user interaction.
3) Clear visual hierarchy
Every screen must answer (at a glance):
- what this page is,
- what the primary action is,
- where the navigation is,
- what is secondary.
4) Grouping must be unambiguous
If spacing is doing grouping work:
- there must be more space around groups than within groups.
5) Feedback and forgiveness
Users should:
- see results of actions quickly,
- understand system status,
- and recover via undo/back/cancel where possible.
Prefer preventing errors over scolding users.
6) Accessibility is part of “beautiful”
Good aesthetics survive:
- keyboard-only use,
- low vision,
- colour‑blindness,
- small screens,
- slow networks.
Default outputs format
When responding, produce: 1. Design brief (bullets) 2. IA + key flows (bullets + simple diagrams if useful) 3. Component inventory (table or list) 4. Design tokens (CSS variables or JSON) 5. Page-level guidance (for each page/section) 6. States & edge cases 7. Implementation notes (HTML structure, CSS approach, ARIA, etc.)
If the user asked for a critique/audit, output:
- issues (grouped by severity),
- fixes,
- and a “next iteration plan”.
The workflow in practice
Step 0 — Gather inputs (fast)
Ask only what’s needed; otherwise assume and state assumptions.
Minimum questions:
- Primary user: who is this for?
- Primary goal: what must they do?
- Business goal: what does success look like?
- Content: what is real copy/data?
- Brand signals: existing colours/logo/type/voice?
- Constraints: tech stack, deadline, accessibility level.
If inputs are missing, create a working brief with explicit assumptions.
Step 1 — Strategy (align intent)
Produce:
- primary + secondary user goals,
- business objectives,
- success metrics,
- constraints/risk.
Step 2 — Scope (decide what exists)
Define:
- pages/screens,
- features,
- content requirements,
- and what is out of scope.
Pick 1–3 key paths (the journeys that matter most). Optimise these first.
Step 3 — Structure (make it findable)
Create:
- sitemap / nav model (global + local nav),
- page purpose statements,
- user flows for key paths.
Rule: navigation labels should be self‑evident; avoid internal jargon.
Step 4 — Skeleton (arrange the UI)
Create:
- wireframes per page,
- component inventory,
- layout constraints (container widths, grids, spacing rhythm),
- and priority order per breakpoint.
Rule: start with the feature/content, not the “app shell”.
Step 5 — Surface (make it beautiful)
Build a consistent system:
- spacing + sizing scale,
- typography scale,
- colour palette + shades,
- radius + border rules,
- elevation/shadow scale,
- icon + illustration style,
- motion rules (optional).
Apply to page comps.
Step 6 — Validate (fast loops)
Run these checks:
- Glance test (5–10 seconds): can someone tell what this is and what to do?
- Key‑path walkthrough: can a first‑time user complete the main task?
- Consistency pass: are tokens respected? is hierarchy consistent?
- Accessibility pass: contrast, focus states, semantics, error messaging.
Step 7 — Hand-off (make it buildable)
Provide:
- tokens,
- component specs (states + spacing + behaviour),
- responsive rules,
- and edge cases.
Default starter system
Use this system unless the project already has one.
Spacing & sizing scale (px)
Use a non-linear scale so choices are easy: 0, 4, 8, 12, 16, 24, 32, 48, 64, 96, 128
Rules:
- pick from the scale; avoid “one-off” numbers.
- for grouping: inside-group spacing < between-group spacing.
Typography scale (px)
Keep it tight: 6–8 sizes is enough.
Suggested:
12caption14small/body-secondary16body20subheading24h330h240h1/hero
Rules:
- default body line-height ~
1.5–1.7. - limit line length for reading (~45–80 characters).
- use weight/colour/spacing before adding new sizes.
Colour system
- define neutrals (backgrounds + text), one primary, and semantic accents.
- define shades up front (e.g., 100–900), don’t generate ad-hoc lightens/darkens.
- “Grey” can be warm or cool; keep a consistent temperature.
Contrast rules:
- normal text target: ≥ 4.5:1
- large text target: ≥ 3:1
Elevation / shadow system
Use 3–5 shadow levels that map to meaning:
- 1: buttons/cards (subtle)
- 2: popovers/menus
- 3: sticky headers
- 4: modals
- 5: high priority overlays
Borders
Prefer:
- spacing,
- subtle shadows,
- or small background changes
over heavy borders.
Empty states
Empty states are a first impression. They must:
- explain what’s empty,
- why it matters,
- and what to do next.
Progressive disclosure
Use these reference files when deeper detail is needed:
- Workflow & deliverables → references/WORKFLOW.md
- Page patterns → references/PAGE-PATTERNS.md
- Audit / critique → references/DESIGN-AUDIT.md
- Usability & navigation → references/USABILITY.md
- Visual design systems → references/VISUAL-DESIGN.md
- Interaction & forms → references/INTERACTION-DESIGN.md
- Information architecture → references/INFORMATION-ARCHITECTURE.md
- Content & microcopy → references/CONTENT-COPY.md
- Responsive rules → references/RESPONSIVE.md
- Accessibility → references/ACCESSIBILITY.md
- Checklists & templates → references/CHECKLISTS.md
Quick search
If running locally:
grep -i "empty state\|hierarchy\|spacing" -n references/*.mdTHE EXACT PROMPT — UX/UI plan
You are designing a website UI/UX.
1) Write a crisp design brief (users, goals, constraints, success metrics).
2) Define information architecture + navigation model.
3) Identify 1–3 key user paths; write step-by-step flows.
4) Produce a component inventory for the key pages.
5) Propose a design token system (spacing, type, colour, radius, shadow) with rules.
6) Describe page layouts (mobile-first) and key interactions.
7) List empty/loading/error states and edge cases.
8) Run a usability + accessibility + consistency pass; revise.
Output must be specific and implementable.
Avoid vague advice.THE EXACT PROMPT — Visual polish pass
Review this UI for visual quality.
- Fix hierarchy (what is primary vs secondary vs tertiary?)
- Fix spacing (grouping clarity; rhythm; alignment)
- Fix typography (scale, weights, line height, line length)
- Fix colour (contrast, palette consistency, accent usage)
- Fix depth (shadows/borders; focus on meaning)
- Improve empty states and microcopy
Return:
1) a list of concrete changes
2) updated tokens (if needed)
3) before/after descriptions of the most important screens.THE EXACT PROMPT — Usability “glance test”
Pretend you have 10 seconds to look at this page.
Answer:
- What is this page?
- Who is it for?
- What are the top 3 things I can do here?
- What is the primary action?
- Where is the navigation?
Then list everything that created a question mark, and propose fixes.THE EXACT PROMPT — Component spec (single component)
Write a build-ready spec for this component.
Include:
- Purpose + when to use
- Anatomy (parts)
- Variants
- States: default/hover/focus/active/disabled/loading/error/success/empty
- Behaviour rules (keyboard + mouse + touch)
- Spacing + typography + colour tokens used
- Accessibility notes (ARIA if needed)
- Edge cases (long text, missing data, localisation)
Keep it concise but unambiguous.THE EXACT PROMPT — Accessibility pass
Review this design for accessibility.
Check:
- text contrast (normal and large text)
- keyboard navigation and focus visibility
- semantic element choices (button vs link vs div)
- form labelling and error announcement
- motion and reduced-motion behaviour
Return:
1) issues grouped by severity
2) concrete fixes (design + implementation)
3) any token changes needed (colours, focus styles)THE EXACT PROMPT — Responsive pass
Define responsive behaviour for this page/component.
For each breakpoint (small phone, large phone, tablet, desktop):
- layout (stack/columns)
- what becomes primary vs secondary
- how text wraps/truncates
- how tables, toolbars, and secondary actions adapt
Then list edge cases (long text, empty, error) and how they render.designing-beautiful-websites
Designs UX/UI for websites and web apps: UX strategy, information architecture, user flows, wireframes, UI systems, and polished visual design.
Quick install
npx skills add https://github.com/tristanmanchester/agent-skills --skill designing-beautiful-websitesUsage
See SKILL.md for the workflow and deliverables.
Accessibility Essentials for Web UX/UI
Use this when designing, auditing, or specifying UI. Accessibility is a quality baseline, not a nice-to-have.
Table of contents
- Non-negotiables
- Colour and contrast
- Keyboard and focus
- Semantic HTML
- Forms and errors
- Motion and animation
- Optional: contrast check script
Non-negotiables
- All interactive elements are reachable via keyboard.
- Focus is visible and logical.
- Text has sufficient contrast.
- Controls have programmatic labels.
- Errors are understandable and recoverable.
Colour and contrast
Targets:
- normal text: ≥ 4.5:1
- large text: ≥ 3:1
Rules:
- don’t rely on colour alone to communicate state (also use icons, text, or patterns).
- if white text forces a coloured background to become too dark and visually dominant, use dark text on a light tint.
Keyboard and focus
Rules:
- focus order follows visual order.
- focus styles are obvious (don’t remove outlines without replacing them).
- modals trap focus and restore it on close.
Semantic HTML
Prefer native elements:
<button>for actions,<a>for navigation.- headings are hierarchical.
- lists are real lists.
- inputs have
<label for=...>.
ARIA rule:
- don’t add ARIA when native semantics already solve it.
Forms and errors
Rules:
- label every input.
- indicate required fields.
- validate clearly and near the field.
- on submit errors, focus the first invalid field.
- error messages must be announced (aria-live / describedby patterns).
Motion and animation
Rules:
- motion should communicate meaning (state change), not just decorate.
- respect reduced motion preferences.
Optional: contrast check script
If tooling is available, run:
python scripts/contrast_check.py "#0f172a" "#ffffff"It prints contrast ratio and pass/fail for normal and large text.
UX/UI Checklists and Templates
Use this for fast QA and consistent outputs.
Table of contents
- Design brief checklist
- IA and navigation checklist
- Wireframe checklist
- Visual system checklist
- Interaction and forms checklist
- Accessibility checklist
- Content checklist
- Responsive checklist
- Pre-launch QA checklist
- Component state matrix template
Design brief checklist
- [ ] Primary user(s) defined
- [ ] Primary user goal and business goal stated
- [ ] Success metrics listed
- [ ] Constraints (tech, time, brand, legal, accessibility) captured
- [ ] Key pages listed
- [ ] Key paths listed
- [ ] Assumptions clearly marked
IA and navigation checklist
- [ ] Top-level nav is short and stable
- [ ] Labels are obvious and consistent
- [ ] Current location is visible (active state / breadcrumbs)
- [ ] Every page has a clear title that matches nav labels
- [ ] Search exists where discovery matters
Wireframe checklist
- [ ] Page has a single primary action (or an explicit reason it doesn’t)
- [ ] Regions are clear (nav, main, secondary)
- [ ] Key path steps are unambiguous
- [ ] Clickable elements are clearly signified
- [ ] Spacing communicates grouping (inside < between)
Visual system checklist
- [ ] Spacing scale defined and used
- [ ] Type scale defined and used
- [ ] Colour palette defined (neutrals, primary, semantic accents)
- [ ] Contrast targets met
- [ ] Radius and elevation systems defined
- [ ] Borders used sparingly
Interaction and forms checklist
- [ ] Inputs have labels
- [ ] Inline validation behaviour defined
- [ ] Errors are actionable, not blaming
- [ ] Destructive actions are reversible or confirmed
- [ ] Feedback is modeless when possible
Accessibility checklist
- [ ] Keyboard navigation works and focus is visible
- [ ] Contrast targets met
- [ ] Not colour-only communication
- [ ] Semantic elements used appropriately
- [ ] Forms announce errors appropriately
Content checklist
- [ ] Headings describe the section
- [ ] Copy is scannable (bullets, short paragraphs)
- [ ] Button labels describe outcomes
- [ ] Jargon and clever labels removed
- [ ] Empty states explain and guide
Responsive checklist
- [ ] Mobile-first layout is viable
- [ ] Primary action remains prominent at all sizes
- [ ] Text doesn’t become too wide to read
- [ ] Tables/toolbars have responsive strategies
- [ ] Touch targets are comfortable
Pre-launch QA checklist
- [ ] Key paths tested end-to-end
- [ ] Loading/empty/error states handled
- [ ] Long text and localisation expansion tested
- [ ] Images have safe fallbacks
- [ ] Performance basics: avoid heavy assets above the fold
- [ ] Cross-browser smoke test
Component state matrix template
For each component:
- Variants:
- States:
- Default
- Hover
- Focus
- Active
- Disabled
- Loading
- Error
- Success
- Empty (if relevant)
- Keyboard behaviour:
- Screen reader notes:
Content and Microcopy for Websites
Use this when you need labels, headings, CTA copy, and error messages that reduce thinking.
Table of contents
- Principles
- Write for scanning
- Naming and labels
- Buttons and calls to action
- Helper text and instructions
- Empty states
- Errors and recovery
Principles
- Words are part of the interface; treat them as design.
- Prefer plain, obvious language over cleverness.
- Reduce cognitive load: fewer words, clearer words, placed near the decision.
Write for scanning
Use:
- short paragraphs,
- bullets,
- meaningful headings,
- emphasis sparingly.
Checklist:
- the first sentence in a section should communicate the point;
- headings should describe the content beneath them;
- avoid walls of text; split into sections.
Naming and labels
Rules:
- use user vocabulary, not internal jargon;
- keep terms consistent across navigation, headings, and buttons;
- avoid marketing names that hide meaning.
Bad → better examples:
- “Solutions” → “Pricing” / “Use cases” / “Services” (be specific)
- “Learn” → “Docs” / “Guides” / “Resources”
- “Continue” → “Create account” / “Choose plan” / “Pay now”
Buttons and calls to action
Rules:
- button text should describe the result (“Generate report”).
- primary CTA is singular; secondary CTAs are visually quieter.
- destructive actions must be clearly labelled (“Delete project”).
Helper text and instructions
Rules:
- put instructions where the decision happens (near the control).
- keep helper text short; link to details if needed.
- don’t rely on placeholder text as the only label.
Empty states
A good empty state includes:
- what this area is for,
- why it matters,
- an example (if helpful),
- and a clear next step.
Errors and recovery
Error message template:
- What happened
- Why it matters (optional)
- What to do next
Rules:
- avoid blame (“You did it wrong”).
- be specific (“Password must be at least 12 characters”).
- preserve user input whenever possible.
- for global errors, point to the field or action that caused it.
UX/UI Design Audit Playbook
Use this when the user asks to critique, review, modernise, or improve an existing website/app UI.
Table of contents
What to collect
- Screens: home, key pages, key flows, states (error/empty/loading)
- Known constraints: brand, tech stack, accessibility target
- Success metrics: conversion, task completion, retention, support tickets
- Primary users: who they are and what they want to do
If you don’t have data, state assumptions.
Audit workflow
1. Define success
- What should users be able to do?
- What does the business care about?
2. Map 1–3 key paths
- Write the flows step-by-step.
- Note every moment of uncertainty or friction.
3. Run a “trunk test” on internal pages Check whether a first-time user can tell:
- what site this is,
- what page this is,
- where they are in the structure,
- where to go next.
4. Heuristic review (fast rubric below) Capture issues as:
- Symptom (what the user experiences)
- Cause (why it happens)
- Fix (concrete change)
5. Systemise fixes Look for repeating causes:
- inconsistent spacing,
- unclear clickability,
- weak hierarchy,
- inconsistent component styles.
6. Propose an iteration plan
- quick wins (1–2 days)
- medium changes (1–2 weeks)
- bigger redesign (multi-week)
Heuristic review rubric
Score each area: ✅ good / ⚠️ needs work / ❌ broken.
Clarity
- Can users tell what the page is for in 10 seconds?
- Is the primary action obvious?
- Are labels self-explanatory?
Hierarchy
- Is there a clear primary/secondary/tertiary structure?
- Does spacing communicate grouping?
- Do headings match content and boundaries?
Navigation and findability
- Is location clear (active states, page titles)?
- Are section labels consistent?
- Is search available where needed?
Interaction quality
- Do controls behave as expected?
- Is feedback immediate and non-disruptive?
- Are errors prevented where possible?
Visual quality
- Is typography consistent and readable?
- Is colour used with restraint and meaning?
- Is depth/border usage calm (not busy)?
Accessibility
- Contrast targets met?
- Keyboard usable?
- Focus visible?
- Labels and errors accessible?
Common root causes
- No defined token system → inconsistent spacing/colours/typography.
- Too many competing CTAs → unclear priority.
- Clever labels → hesitation and misclicks.
- Weak affordances → “is this clickable?” confusion.
- Overuse of borders → busy and cluttered look.
- Missing states → broken first impressions (empty/loading/error).
How to present results
Recommended structure: 1. Executive summary: 5–10 bullets 2. Top issues by severity
- Critical (blocks key path)
- Major (causes hesitation)
- Minor (polish)
3. Screens/flows reviewed 4. Recommendations
- system fixes (tokens/components)
- page fixes
5. Next iteration plan
- quick wins
- medium
- long term
Information Architecture for Websites
Use this when you need to structure pages, navigation, labels, and findability.
Table of contents
- Core concepts
- Sitemaps and navigation models
- Labelling and naming
- Search
- Page purpose statements
- IA deliverables
Core concepts
- Findability beats novelty: users rarely explore; they look for a path to the goal.
- Clear categories reduce thinking: if top-level sections are obvious, the rest becomes easy.
- Structure and skeleton are connected: IA decisions affect layouts, and layouts expose IA problems.
Sitemaps and navigation models
Choose a model:
- Marketing site: Home, Product, Pricing, Docs/Resources, About, Contact.
- Content site: Sections by topic, strong search, archive views.
- Web app: Tasks and objects drive navigation (not departments or internal team names).
Rules:
- Keep top-level navigation stable and short.
- Use local navigation for depth (subsections) rather than exploding global nav.
- Always make it clear where the user is (active states, breadcrumbs when useful).
Labelling and naming
Rules:
- Use plain language and familiar terms.
- Prefer user vocabulary over internal vocabulary.
- Avoid clever names that require explanation.
- Keep labels consistent across the site.
Tests:
- Can someone guess what they will see after clicking the link?
- Does the label match the page title?
Search
Add search if:
- users might not know what the site calls something,
- content is large or frequently updated,
- or there are many objects (products, docs, posts, people).
Rules:
- Put search where users expect it.
- Support partial matches and forgiving input.
- Results should be scannable: highlight matches, show context snippets.
Page purpose statements
For every key page, write one sentence:
- “This page lets the user ____ so they can ____.”
If you can’t write it, the page is probably trying to do too much.
IA deliverables
- Sitemap: pages and hierarchy.
- Navigation model: global + local nav rules.
- Label glossary: canonical terms (and forbidden synonyms).
- Key-path entry points: where journeys start.
- Search behaviour: placement, results design, empty results.
Interaction Design for Websites
Use this when you need behaviour rules, form patterns, error handling, and clear feedback.
Table of contents
- Interaction principles
- Affordances and signifiers
- Direct manipulation and feedback
- Preventing errors
- Dialogs, confirmations, and destructive actions
- Forms
- States and edge cases
Interaction principles
- Make expectations explicit: the UI “promises” behaviour through its visuals; always deliver on that promise.
- Prefer recognition over recall: show options and context; don’t make people memorise.
- Feedback is part of the interaction: users should always know what happened and what happens next.
- Prevent errors: the best error message is the one you never need.
- Keep users in flow: avoid interruptive patterns unless risk is truly high.
Affordances and signifiers
Affordances are what a control appears to do.
Rules:
- controls must look like controls (buttons, links, inputs); don’t rely on hover to reveal affordance;
- interactive areas must have clear hover/focus/active states;
- don’t use the same visual style for interactive and non-interactive elements.
Common traps:
- decorative icons that look clickable,
- cards that are clickable with no signifier,
- “link-like” coloured text that isn’t a link.
Direct manipulation and feedback
When possible, let users act directly on visible objects and see results immediately.
Patterns:
- inline editing (instead of separate edit screens),
- previewing outcomes before committing,
- drag/drop reordering with clear drop targets,
- immediate visual confirmation for actions.
Modeless feedback (preferred)
Use persistent, inline feedback that doesn’t stop the user:
- status badges,
- inline validation,
- progress indicators,
- subtle toasts (with undo when appropriate).
Avoid:
- frequent blocking dialogs,
- errors that appear only after submission,
- vague spinners with no context.
Preventing errors
Three levels of defence (use in order): 1. Make errors impossible: constrain inputs, use pickers, infer values. 2. Make errors unlikely: smart defaults, suggestions, previews. 3. Make recovery easy: undo, clear explanations, safe fallbacks.
Examples:
- auto-format phone numbers and dates;
- look up postcode from address (when feasible);
- disable impossible actions and explain why.
Dialogs, confirmations, and destructive actions
Principle: don’t make users confirm things they don’t understand.
Use confirmations when:
- the action is destructive and not easily reversible,
- the user might trigger it accidentally,
- the impact is significant.
Confirmation copy should:
- name the thing being affected,
- state the impact,
- offer a safe escape.
Prefer:
- undo (best),
- soft delete,
- preview,
- two-step destructive actions (e.g., “type DELETE”).
Forms
Anatomy
For each field:
- label (required),
- input,
- help text (optional),
- validation message (conditional).
Layout and grouping
Rules:
- group related fields; separate groups with extra spacing;
- labels should feel attached to inputs (tight spacing);
- align fields and controls on a clear grid;
- keep forms as short as possible.
Validation
Preferred:
- validate inline after interaction (blur) and on submit;
- show errors near the field;
- keep messages human and actionable.
Avoid:
- error summaries with no field mapping,
- clearing user input after an error,
- blaming the user.
Defaults and choice architecture
Rules:
- pick sensible defaults based on likely user intent;
- for long lists, provide search or typeahead;
- don’t force a choice when “none” is valid.
Accessibility essentials
- every input has a label associated with it;
- errors are announced to assistive tech;
- focus moves to the first error on submit;
- keyboard navigation works logically.
States and edge cases
Every screen/component should define:
- Loading: what is loading? how long? skeleton or spinner?
- Empty: why empty? what next? hide irrelevant controls?
- Error: what happened? retry? alternative path?
- Success: what changed? next action?
- Disabled: why disabled? what enables it?
Edge cases checklist:
- long labels, long values, localisation (text expansion),
- missing avatars/images,
- permissions and read-only modes,
- offline/slow network,
- partial data.
Common Website Page Patterns
Use this when you need concrete, reliable page structures (landing pages, pricing, dashboards, settings).
Table of contents
- Landing page
- Pricing page
- Documentation / resources
- Signup / onboarding
- Dashboard
- Settings page
- Search results
Landing page
Goal: communicate value quickly and move users to the next step.
Recommended structure: 1. Header: logo, top nav (few items), primary CTA. 2. Hero: clear headline, supporting subhead, primary CTA, optional secondary CTA. 3. Trust: logos, metrics, short testimonial. 4. Benefits: 3–6 benefit cards (outcomes, not features). 5. How it works: 3-step explanation or short flow. 6. Use cases (optional): choose 2–4, not a long list. 7. Social proof: testimonials/case studies. 8. FAQ: reduce last-minute hesitation. 9. Footer: secondary nav, legal, contact.
Hierarchy rules:
- headline must be understandable without context;
- primary CTA should repeat (but don’t spam it);
- use scannable chunks; avoid long paragraphs.
Common mistakes:
- vague headline that could fit any product;
- multiple competing CTAs with equal weight;
- decorative hero imagery that doesn’t support meaning.
Pricing page
Goal: help users choose confidently.
Recommended structure:
- short intro: who each plan is for.
- plan cards: 2–4 plans max.
- highlight recommended plan only if it truly is.
- feature comparison: high-signal features, grouped.
- FAQ: billing, cancellation, support.
Rules:
- make the recommended option the easiest choice, not a trick.
- clarify billing period and what happens on renewal.
- avoid footnotes that hide critical limitations.
Documentation / resources
Goal: help users find answers quickly.
Recommended structure:
- search (prominent).
- categories with clear labels.
- “Getting started” path.
- popular tasks (top queries).
Rules:
- content titles must describe the question they answer.
- show last updated dates if freshness matters.
Signup / onboarding
Goal: reduce friction and uncertainty.
Recommended structure:
- keep fields minimal.
- explain why you’re asking for each non-obvious field.
- show progress if multi-step.
Rules:
- preserve inputs on error.
- show password requirements up front.
- offer SSO/social login only if it’s reliable.
Dashboard
Goal: help users act, not admire charts.
Recommended structure:
- page title + primary action.
- key metrics summary (3–6 max).
- recent activity / next steps.
- deeper sections below (charts, tables).
Rules:
- define an information hierarchy; don’t present everything equally.
- density is okay, but spacing must still communicate grouping.
- tables need sorting/filtering conventions and empty states.
Settings page
Goal: safe changes with clear consequences.
Recommended structure:
- group settings by theme.
- keep destructive actions separated and clearly labelled.
- show current values.
Rules:
- avoid auto-saving unless feedback is explicit.
- confirmations only when irreversible.
Search results
Goal: help users compare and choose quickly.
Recommended structure:
- search box persists with query.
- result count + filters.
- scannable results: title, key metadata, snippet.
- empty results guidance: suggestions, broaden filters.
Rules:
- keep filters understandable; avoid internal categories.
- show what filters are active.
Responsive Layout Rules
Use this when you need mobile-first layouts, breakpoint decisions, and component behaviour across screen sizes.
Table of contents
- Core rules
- Mobile-first workflow
- Containers, columns, and reading width
- Independent scaling
- Component responsivity
- Responsive navigation
- Testing checklist
Core rules
- Design for constraints first; expand later.
- Prioritise content and primary actions at every breakpoint.
- Don’t squeeze desktop UI onto mobile; reflow it.
Mobile-first workflow
1. Start at ~360–420px width. 2. Design key pages and key paths. 3. Expand to tablet and desktop and fix what felt like a compromise.
If you’re stuck designing a “small” UI on a wide canvas, shrink the canvas.
Containers, columns, and reading width
Rules:
- Reading-heavy sections need a max width; wide text is hard to scan.
- Don’t make everything full-width just because the header is full-width.
- If a layout feels too wide, split into columns instead of stretching content.
Independent scaling
Avoid purely proportional scaling. As screens shrink:
- large elements should shrink faster than small elements,
- spacing should compress, but not uniformly,
- component padding often needs to tighten more than font size.
Rule:
- fine-tune properties independently; don’t treat the UI as a zoomed image.
Component responsivity
For each component, define:
- how it reflows (stack vs inline),
- how it truncates or wraps text,
- how density changes,
- touch target rules,
- and what happens to secondary actions.
Examples:
- tables → switch to cards, stacked rows, or horizontal scrolling with clear affordance.
- toolbars → move secondary actions into an overflow menu.
Responsive navigation
Rules:
- keep primary navigation discoverable;
- avoid hiding essential sections behind deep menus on desktop;
- on mobile, use patterns users recognise (tabs, bottom nav, hamburger) based on app type.
Testing checklist
- breakpoints: small phone, large phone, tablet, desktop, wide desktop
- text expansion: +30% length (localisation)
- touch: tap targets and spacing
- keyboard: focus order and visible focus
- content extremes: long titles, empty lists, huge numbers
Usability for Websites
Use this when you need to diagnose confusion, improve navigation, or make an interface feel effortless.
Table of contents
- Usability mindset
- Design for scanning
- Make choices mindless
- Navigation that users trust
- Make clickability obvious
- Reduce noise and distractions
- Microcopy and naming
- Quick tests
- Common failure patterns
Usability mindset
Users rarely read; they skim, then pick the first option that seems good enough. Your job is to make the “good enough” option the right one.
Rules of thumb:
- prefer clarity over persuasion;
- remove uncertainty;
- don’t punish users for mistakes;
- don’t surprise users with non-standard behaviour.
Design for scanning
Treat pages like signage. Help users understand the page quickly by:
- using conventions,
- creating strong visual hierarchy,
- dividing pages into clear regions,
- formatting content for scanning.
Visual hierarchy checklist
Every key page should be legible as: 1. page name/purpose, 2. primary action, 3. primary content, 4. secondary actions, 5. supporting info.
Common fixes:
- make the primary CTA the most visually prominent interactive element;
- ensure headings describe the content underneath them;
- use consistent heading sizes and spacing rules;
- avoid placing headings so they “span” unrelated content.
Clear regions checklist
At a glance, a user should be able to point and say:
- “navigation”,
- “main content”,
- “things I can do”,
- “supporting info”,
- “promotions/ads (if any)”.
If the page can’t be chunked, simplify the layout and reduce competing elements.
Make choices mindless
“Fewer clicks” is less important than “easier clicks”. Multiple easy, confident selections beat one confusing choice.
Information scent
Links and buttons should describe the result of clicking. Users should feel they are moving closer to the goal at every step.
Checklist:
- link text is descriptive, not “Click here”;
- button labels describe outcomes (“Create invoice”, not “Submit”);
- navigation labels match user language;
- the current location is visible (active states, breadcrumbs where needed).
Navigation that users trust
Navigation should answer:
- where am I?
- what’s here?
- where can I go next?
Global navigation
Rules:
- keep top-level sections stable across the site;
- use familiar placement (header/top bar or left nav);
- avoid hiding primary nav behind multiple clicks on desktop.
Page naming
Every page needs a clear name. It should:
- be near the top of the main content region,
- match what the user clicked,
- use plain language.
Search
If users can arrive with vague intent, search is not optional. Rules:
- put search where users expect it;
- support forgiving input (typos, partial matches);
- show results that are easy to scan.
Make clickability obvious
Users should never have to think:
- “is this clickable?”
Rules:
- interactive elements must look interactive:
- buttons look like buttons,
- links look like links,
- tabs look like tabs.
- don’t make plain text look like a link.
- keep click targets comfortably large.
Common pitfalls:
- entire cards being clickable with no signifier;
- “ghost” buttons that look like secondary text;
- icons with unclear meaning.
Reduce noise and distractions
Noise forces thinking.
Checklist:
- remove decorative elements that compete with primary content;
- avoid too many colours, weights, and border styles;
- reduce repeated CTAs;
- limit animation to meaning (status/feedback).
Microcopy and naming
Words are UI.
Rules:
- choose “obvious” names over cute/clever names;
- use labels users already know;
- keep instructions short and close to the control;
- remove needless words.
Error copy:
- explain what happened,
- why it matters,
- what to do next.
Never scold the user.
Quick tests
Glance test (10 seconds)
Show a screen for 10 seconds. Ask:
- what is this?
- who is it for?
- what can you do here?
- what is the primary action?
- where is the navigation?
If answers vary, fix hierarchy and labels.
“Trunk test” (first-time comprehension)
Give someone a random internal page (not the home page). Ask them to identify:
- what site is this?
- what page is this?
- what are the main sections?
- where are they in the structure?
- how can they search?
If they can’t answer quickly, fix:
- site ID/branding placement,
- page naming,
- nav structure,
- and visual hierarchy.
Five-minute usability test (DIY)
1. Give a realistic task (from a key path). 2. Ask the participant to narrate what they expect will happen. 3. Stay silent; observe confusion. 4. After, ask:
- what was hardest?
- what surprised you?
- what did you expect instead?
You’ll learn enough from 3–5 participants to make meaningful improvements.
Common failure patterns
- Everything is “important” → nothing stands out; fix hierarchy.
- Too many words → users skip; tighten copy and use bullets.
- Clever labels → users hesitate; rename.
- Hidden primary action → make the next step obvious.
- Unclear grouping → adjust spacing; add separators only if needed.
- Weak click signifiers → use conventional styling.
Visual Design Systems for Websites
Use this when you need to make a UI feel polished and coherent (spacing, typography, colour, depth, imagery).
Table of contents
- Start with a system
- Layout and spacing
- Typography
- Colour
- Depth, borders, and elevation
- Working with images
- Finishing touches
- Reference token starter (CSS)
Start with a system
Beautiful interfaces look “effortless” because decisions are constrained.
Rules:
- choose a spacing scale, type scale, and colour palette before polishing screens;
- use tokens in implementation (CSS variables / design tokens), not one-off values;
- if you add a new token, it must have a reason and a usage rule.
Layout and spacing
Start with too much whitespace
A reliable way to reach “clean” is: 1. give elements more room than you think they need, 2. then remove whitespace until the layout feels tight without feeling cramped.
Dense layouts are sometimes correct (dashboards, data-heavy tools), but density should be a deliberate choice.
Establish a spacing and sizing scale
Avoid pixel-by-pixel tweaking. Pick a non-linear scale where adjacent values are meaningfully different.
Suggested scale (px): 0, 4, 8, 12, 16, 24, 32, 48, 64, 96, 128
Rules:
- no new spacing values without a strong reason;
- “try next value up/down” should usually be the right adjustment;
- prefer padding and whitespace over borders.
Avoid ambiguous spacing
If spacing is the only grouping cue:
- keep inside-group spacing smaller than between-group spacing.
Common examples:
- form labels must feel attached to their inputs;
- headings must feel attached to the section they introduce;
- list items need separation that doesn’t look like line-height.
You don’t have to fill the whole screen
Wide content is harder to read and parse.
Rules:
- choose a sensible max width for reading-heavy sections;
- don’t expand components just because there is empty space;
- when a section needs more visual weight, use hierarchy (type/spacing), not width.
Mobile-first technique:
- design on a narrow canvas first (~360–420px), then expand.
Alignment and rhythm
- Align to a small set of vertical anchors (grid lines, baseline rhythm).
- Prefer consistent edge alignment over “centering everything”.
- Use repeated spacing patterns so the page feels calm.
Typography
Establish a type scale
Most UIs use too many font sizes.
Recommended: 6–8 sizes, named. Example (px):
12caption14small16base20lg24xl302xl403xl
Rules:
- use weight, colour, and spacing before adding sizes;
- define line-height per category (body vs headings);
- keep reading line length ~45–80 characters.
Weight and contrast
- Body text needs enough contrast against the background.
- Use heavier weight or larger size instead of pure colour changes for hierarchy.
Fonts (pragmatic defaults)
- Use 1 font family for most UI.
- If using a second font, reserve it for display/brand moments.
- Avoid ultra-thin weights for text.
Colour
Build palettes with shades
Define shades up front so you don’t end up with dozens of near-identical colours.
Rules:
- define a neutral scale for backgrounds and text;
- define one primary brand colour with shades;
- define semantic accents (success/warn/danger/info) with shades;
- avoid algorithmic lightening/darkening for production tokens.
A practical shade naming scheme: 100, 200, 300, 400, 500, 600, 700, 800, 900
Typical usage:
900–700for text600–400for borders/icons/active states300–100for subtle backgrounds
Greys have temperature
True grey is rare; “greys” often lean warm or cool. Pick a temperature and keep it consistent.
Rule:
- slightly increase saturation in very light and very dark neutrals so they don’t feel washed out.
Don’t let lightness kill saturation
Very light or very dark colours can look dull if saturation isn’t adjusted.
Practical approach:
- for lighter shades: raise saturation slightly as lightness rises;
- for darker shades: raise saturation slightly as lightness falls.
Adjust perceived brightness with small hue rotation
Different hues feel inherently brighter. To create lighter/darker shades without “washing out” a colour:
- rotate hue slightly (small changes only; keep within ~20–30°).
Accessible contrast without ugly UI
Targets:
- normal text: ≥ 4.5:1
- large text: ≥ 3:1
If white text on a coloured background forces the background to become too dark and dominant:
- flip the contrast: use dark coloured text on a light tinted background.
For coloured text on coloured backgrounds:
- consider shifting the text hue towards a brighter hue while meeting contrast.
Depth, borders, and elevation
Emulate a light source
To make elevation feel real:
- top edges are slightly lighter;
- shadows fall below the element;
- keep blur modest; sharp-ish edges feel more natural.
Use shadows to convey meaning
Shadows are not decoration; they indicate z-position and focus.
Guidelines:
- subtle shadows for cards/buttons,
- stronger shadows for popovers,
- strongest for modals.
Define a small elevation system (3–5 shadows) and reuse them.
Use fewer borders
Borders can make a UI feel busy. Try, in this order: 1. more spacing, 2. slight background difference, 3. subtle shadow, 4. border (last resort).
Working with images
Rules:
- use genuinely good images; low-quality images poison an otherwise clean UI;
- ensure text on images has consistent contrast (overlay, gradient, or avoid);
- beware user-uploaded images: plan for weird crops, bad lighting, and clashing colours.
Practical strategies:
- enforce aspect ratios;
- use object-fit with focal point hints;
- add subtle background or border radius consistency.
Finishing touches
Empty states
Don’t ship a feature without its empty state. An empty state should:
- explain what this section is for,
- show an example,
- and highlight the next action.
Also consider hiding irrelevant controls (filters/tabs) until there is data.
Accent borders
To make UI feel “designed” without adding noise:
- use a thin accent border on cards/alerts;
- keep contrast subtle;
- tie accent use to meaning (status, category).
Decorated backgrounds (subtle)
Background patterns and shapes can add polish. Rules:
- keep contrast low;
- keep decoration out of the reading path;
- use it to frame sections, not compete with content.
Reference token starter (CSS)
:root {
/* Spacing */
--space-0: 0px;
--space-1: 4px;
--space-2: 8px;
--space-3: 12px;
--space-4: 16px;
--space-5: 24px;
--space-6: 32px;
--space-7: 48px;
--space-8: 64px;
--space-9: 96px;
--space-10: 128px;
/* Type scale */
--font-0: 12px;
--font-1: 14px;
--font-2: 16px;
--font-3: 20px;
--font-4: 24px;
--font-5: 30px;
--font-6: 40px;
/* Radius */
--radius-1: 6px;
--radius-2: 10px;
--radius-3: 16px;
/* Elevation (examples, tune to palette) */
--shadow-1: 0 1px 2px rgba(0,0,0,0.08);
--shadow-2: 0 4px 10px rgba(0,0,0,0.10);
--shadow-3: 0 10px 25px rgba(0,0,0,0.12);
--shadow-4: 0 20px 50px rgba(0,0,0,0.16);
/* Neutral palette (example placeholders) */
--neutral-0: #ffffff;
--neutral-50: #f8fafc;
--neutral-100: #f1f5f9;
--neutral-200: #e2e8f0;
--neutral-300: #cbd5e1;
--neutral-600: #475569;
--neutral-800: #1f2937;
--neutral-900: #0f172a;
}Use a real palette for your project; don’t ship placeholder colours.
UX/UI Workflow for Websites
Use this when you need an end-to-end plan, deliverables, or a repeatable way to go from vague intent → shippable design.
Table of contents
- Operating principles
- Phase 0: Define the problem
- Phase 1: Users and goals
- Phase 2: Scope and requirements
- Phase 3: Information architecture and navigation
- Phase 4: Interaction model
- Phase 5: Skeleton (wireframes and layout)
- Phase 6: Surface (visual system and comps)
- Phase 7: Validate and iterate
- Phase 8: Handoff
- Templates
Operating principles
- Build from intent to pixels: decisions about colour and layout are constrained by goals, content, and flows.
- Work iteratively, not sequentially: higher-level design can reveal missing lower-level decisions. Expect to revisit.
- Optimise the key paths first: a site that nails the primary journeys beats a site with 40 mediocre pages.
- Design for scanning: on the web, users skim and select; structure and hierarchy are the design.
- System > screens: design tokens + components prevent “one-off UI” and accelerate implementation.
Phase 0: Define the problem
Output: one-page design brief.
Checklist:
- Who is the product/site for?
- What is the #1 outcome the user must achieve?
- What is the #1 business outcome?
- What constraints exist (tech, brand, legal, accessibility, time)?
- What is the current baseline (what works, what fails)?
Rules:
- If details are missing, write assumptions explicitly.
- Tie design decisions to outcomes (conversion, retention, comprehension, task completion).
Phase 1: Users and goals
Pick a lightweight method based on time.
Option A: Persona-lite (fast)
Create 1–2 persona-lites that capture:
- goals (why they’re here),
- context (device, environment, time pressure),
- anxieties/risks (what makes them hesitate),
- capabilities (experience level, accessibility needs).
Option B: Job story (fastest)
Format:
- When [situation]
- I want [motivation]
- So I can [expected outcome]
Option C: Full persona + scenario (when high stakes)
Write a short narrative of an ideal experience that emphasises goals and context.
Rules:
- Goals before tasks: tasks are symptoms; goals drive prioritisation.
- Prefer a small “cast” with clear priority:
- primary persona (design target),
- secondary personas (supported, but not driving the UI).
Phase 2: Scope and requirements
Output: scope list + key paths.
Steps: 1. List pages/screens and major features. 2. Do a content inventory (what copy, images, data exist?). 3. Define 1–3 key paths.
Key path examples:
- Landing → pricing → signup
- Search → filter → item detail → checkout
- Dashboard → create report → export/share
Rules:
- If everything is a priority, nothing is. Pick the journeys that matter.
- Delay “nice to have” features until the key paths are frictionless.
Phase 3: Information architecture and navigation
Output: IA diagram + navigation model + labels.
Checklist:
- Global nav: top-level sections (5–7 is usually enough).
- Local nav: within a section, how do users move laterally?
- Search: if discovery matters, define where search lives and how results work.
- Page naming: every page needs a clear name that matches the user’s mental model.
Rules:
- Labels must be obvious. Avoid internal jargon and clever marketing names.
- Prefer recognition over recall: show choices; don’t force memory.
- Keep navigation consistent across pages.
Phase 4: Interaction model
Output: flows + interaction rules + state model.
Steps: 1. For each key path, write the step-by-step flow. 2. Define interaction patterns:
- forms,
- filtering/sorting,
- selection,
- editing,
- confirmations/destructive actions.
3. Define states for each key screen:
- loading,
- empty,
- error,
- success,
- partial data,
- permissions.
Rules:
- Prefer preventing errors (smart defaults, constraints) over showing errors.
- Prefer modeless feedback (inline status, previews) over disruptive dialogs.
Phase 5: Skeleton (wireframes and layout)
Output: wireframes + component inventory.
Steps: 1. Start with a real feature/content block (not a nav bar). 2. Place information in priority order. 3. Establish page regions:
- site ID,
- navigation,
- primary content,
- secondary content,
- calls to action.
4. Define responsive layout constraints:
- max content width,
- breakpoints,
- column strategy.
Rules:
- A page should be parsable at a glance into clearly defined areas.
- Make click targets and interactive affordances obvious.
Phase 6: Surface (visual system and comps)
Output: tokens + component library + page comps.
Steps: 1. Create tokens:
- spacing/sizing,
- type scale,
- colours (with shades),
- radius,
- elevation.
2. Define components and variants. 3. Apply to key pages first.
Rules:
- Constrain choices. Systems beat arbitrary numbers.
- Use spacing to clarify grouping.
- Use colour sparingly for meaning (actions and status), not decoration.
Phase 7: Validate and iterate
Output: issues + fixes + updated design.
Use quick, repeatable tests:
- Glance test: in 10 seconds, can someone tell what it is and what to do?
- Key-path walkthrough: can a first-time user complete the journey?
- Edge case sweep: long text, missing data, errors, empty.
- Accessibility sweep: contrast, focus, keyboard, semantics.
Iteration rule:
- Make the smallest set of changes that remove the largest confusion.
Phase 8: Handoff
Output: build-ready package.
Include:
- tokens (CSS variables or JSON),
- component specs (including states),
- responsive rules,
- accessibility notes,
- content rules (copy lengths, truncation),
- and acceptance criteria for key paths.
Templates
Template: Design brief (one page)
- Product/site:
- Primary user:
- Primary user goal:
- Business goal:
- Success metrics:
- Constraints:
- Key pages:
- Key paths:
- Brand traits (3–5 adjectives):
- Risks/unknowns:
Template: Key path flow
- Goal:
- Entry points:
- Steps:
1. 2. 3.
- Decisions/branches:
- Failure states:
- Success confirmation:
Template: Component inventory
For each component:
- name,
- purpose,
- variants,
- states,
- dependencies (tokens, subcomponents).
Template: State model (per page)
- Loading:
- Empty:
- Error:
- Success:
- Partial data:
- Permissions:
#!/usr/bin/env python3
"""WCAG contrast ratio checker.
Usage:
python scripts/contrast_check.py "#0f172a" "#ffffff"
Outputs the contrast ratio and whether it passes WCAG AA for:
- normal text (>= 4.5:1)
- large text (>= 3:1)
Exit codes:
- 0 if passes normal text threshold
- 1 otherwise
"""
from __future__ import annotations
import re
import sys
from dataclasses import dataclass
@dataclass(frozen=True)
class RGB:
r: float # 0..1
g: float # 0..1
b: float # 0..1
HEX_RE = re.compile(r"^#?(?P<h>[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$")
def parse_hex_colour(s: str) -> RGB:
m = HEX_RE.match(s.strip())
if not m:
raise ValueError(f"Invalid hex colour: {s!r}. Expected #RGB or #RRGGBB.")
h = m.group("h")
if len(h) == 3:
h = "".join(ch * 2 for ch in h)
r = int(h[0:2], 16) / 255.0
g = int(h[2:4], 16) / 255.0
b = int(h[4:6], 16) / 255.0
return RGB(r, g, b)
def srgb_to_linear(c: float) -> float:
# WCAG uses the sRGB companding function.
if c <= 0.04045:
return c / 12.92
return ((c + 0.055) / 1.055) ** 2.4
def relative_luminance(rgb: RGB) -> float:
r_lin = srgb_to_linear(rgb.r)
g_lin = srgb_to_linear(rgb.g)
b_lin = srgb_to_linear(rgb.b)
# ITU-R BT.709
return 0.2126 * r_lin + 0.7152 * g_lin + 0.0722 * b_lin
def contrast_ratio(c1: RGB, c2: RGB) -> float:
l1 = relative_luminance(c1)
l2 = relative_luminance(c2)
lighter = max(l1, l2)
darker = min(l1, l2)
return (lighter + 0.05) / (darker + 0.05)
def main(argv: list[str]) -> int:
if len(argv) != 3:
print(__doc__.strip())
return 2
fg_s, bg_s = argv[1], argv[2]
try:
fg = parse_hex_colour(fg_s)
bg = parse_hex_colour(bg_s)
except ValueError as e:
print(f"Error: {e}")
return 2
ratio = contrast_ratio(fg, bg)
normal_ok = ratio >= 4.5
large_ok = ratio >= 3.0
print(f"Foreground: {fg_s} Background: {bg_s}")
print(f"Contrast ratio: {ratio:.2f}:1")
print(f"Normal text (>= 4.5): {'PASS' if normal_ok else 'FAIL'}")
print(f"Large text (>= 3.0): {'PASS' if large_ok else 'FAIL'}")
return 0 if normal_ok else 1
if __name__ == "__main__":
raise SystemExit(main(sys.argv))
Related skills
FAQ
What is designing-beautiful-websites?
>-
When should I use designing-beautiful-websites?
>-
Is designing-beautiful-websites safe to install?
Review the Security Audits panel on this page before production use.