Style an interface that changes as people use it
In this course, dynamic CSS means styles that respond to content, user actions, preferences and interface state. Build a fictional Ambala campus workshop dashboard with an agenda, a course filter, an expandable information area and reading themes. A visitor should be able to find one workshop date, recognise it as saved and switch the page to a reading theme they prefer. Start with usable HTML and a readable default stylesheet. Then add state where the interface needs to communicate a change.
Separate three decisions. First decide what should respond to available space, such as how many agenda cards fit in a row. Next decide which interactions can use existing browser states, such as keyboard focus or an open details element. Then choose which actions need values controlled by JavaScript, such as a saved workshop or a user-selected theme. Give data and behaviour their own logic, and let CSS represent the result. For example, saving a workshop is an action whose outcome can be indicated with text and a matching style.
Create a repeatable project setup
Use a demo page with three fictional courses, a heading, a settings button and cards with date, description and action. Make one card title wrap, give another a thumbnail and put a longer summary in the third. Test the initial page with JavaScript turned off and define which features should still work. The agenda and links should remain available. A theme toggle requires its associated behaviour. Use small files that a classmate can open in a local browser without entering real student information.
Control repeated choices with CSS custom properties
Custom properties hold values CSS rules can refer to with var. You can define tokens for text, canvas background, card surface, border and action colour. Name a token for its role, such as --text-muted or --surface, so the role is still meaningful when dark mode uses a different value. Declare shared defaults on the root element. Components can refer to those tokens rather than choosing new colours independently.
A custom property follows the cascade and typically inherits. A property set on a dashboard section can override the theme value for descendants, while content elsewhere keeps the root value. Try a light page with a dark event panel. Scope the panel tokens to its own wrapper. Inspect the background and text of both components in developer tools. If the whole site changes, find the selector that sets the override. Scope this choice to the correct component rather than compensating with another global rule.
:root {
--canvas: #f3f6fc;
--surface: #fff;
--text: #1a2740;
--accent: #154f9c;
}
:root[data-theme="dark"] {
--canvas: #141d2a;
--surface: #202c3d;
--text: #f4f7fc;
--accent: #a5c9ff;
}
body {
background: var(--canvas);
color: var(--text);
}
.workshop-card {
background: var(--surface);
}
Check a fallback in the browser
Set a badge's foreground with var and a fallback value. Remove the property definition temporarily, then inspect the computed foreground. The fallback is useful when a custom property has not been provided. Also test when a defined property contains a value unsuitable for the actual CSS property. Writing a fallback inside var is not a general-purpose validator for invalid input. Keep tokens appropriate to their role and inspect the finished computed value.
Connect state to CSS with a clear interface
Use attributes or classes to express meaningful state. A details element exposes its open attribute when the visitor expands it. Style its summary differently when open by targeting that attribute. For a custom save button, use a real button and update aria-pressed to represent the current toggled choice. Style the pressed state from the same attribute and update its visible label where needed. The visual cue and accessible state should describe the same result throughout the interaction.
Avoid scattering unrelated classes through every element when one state on a useful ancestor can express the design. For example, setting a data-theme value on the document root provides a shared theme decision. A selected card can own its own saved state instead. The location of the state tells you which part of the page should respond. In developer tools, change the value on the intended element and observe which components react without running the application.
Design a save interaction with evidence
Give each workshop a button labelled with the action and the workshop it affects. For a toggle with a stable label, aria-pressed can communicate whether that workshop is saved. Set the toggled style using a border, stronger text or an indicator. Check that someone can recognise the state without relying on a blue or green colour difference. Press the button twice using the keyboard and confirm each transition. A small script can keep track of saved IDs for the duration of the demo.
Keep the relationship between disabled and inactive clear
A future workshop might show “Registration not open” and a date. Consider whether a button is needed at all before registration is available. If a disabled control is appropriate, use the actual disabled state instead of only lowering its opacity. Provide the reason in visible text. If a pending state only lasts while a request is being processed, restore the action or show what happened when it finishes. Check that the disabled-looking style never leaves a live action unintentionally clickable.
Add a theme preference without making the page dependent on it
Respect a user's device preference at the default entry point. A prefers-color-scheme media query can apply dark tokens when the system indicates dark mode. If your demo allows the visitor to choose a theme explicitly, define how that choice interacts with the system default. A workable rule is that an explicit light or dark selection takes priority, and a reset returns to the system preference. Apply the same token names so each component can inherit the final values.
An interface with three choices can use a select labelled “Theme” with System, Light and Dark. On selection, set the root's data-theme attribute for an explicit choice or remove it for System. If you add persistence, use a small validated value in browser storage. Handle absent or unavailable storage by retaining the default and keeping the interface usable. Do not store unrelated data while implementing one display preference. The theme choice should remain consistent across components and understandable even after a reload.
Audit both colour schemes component by component
Compare the same card in light and dark mode. Read the date, title, help note and link, inspect which token each one uses and check their contrast against the actual background. Put focus on the action and verify the focus border in each mode. Check any SVG icons or images used beside text. Icons can sometimes inherit currentColor, while artwork may need a surface or version appropriate to the scheme. The success condition is that the visitor can still use the page with their preferred theme.
Debug a theme that changes only half the page
Find one panel that stays too bright when you turn dark mode on. Inspect its computed background and the rule that sets it. A hard-coded white background bypasses the surface token. Switch that component to the right token, then check whether its subtle border and body text also depend on fixed colours. Repeat for the form and empty-results state. A screen with all cards loaded can look consistent while a status component still has an old colour.
Adjust layouts as the dashboard changes width
Start with a usable one-column arrangement. Allow the card group to adapt as its container grows, and add a media query if the entire page needs a new arrangement at a larger viewport. Check whether the important width is the viewport or the available area inside the dashboard. A card section beside navigation has less room than a full-width catalogue even on the same device. Use flexible sizing before adding many breakpoints.
Use clamp with values that have a clear job. For example, a section title can have a size range between two readable bounds with a fluid middle value. Test the lower and upper ends of the range. A fluid size should remain understandable with zoom or larger text. Check whether a long card label still wraps naturally. CSS can adapt the visual layout but the underlying order should still make sense to someone using a keyboard or a screen reader.
Compare width-driven and state-driven changes
On a narrow view, stack the agenda filters because they need space. When a visitor chooses a topic with no matching lessons, display a message instead of an empty panel. The first change responds to layout conditions. The second change represents a result of the user action. Give each concern a clear home. A media query does not need to know whether workshops matched. An empty-state component still needs styles that adapt to the available screen width.
Reproduce a compact layout problem
Use a narrow preview and long sample workshop titles. Add a filter count that becomes three words instead of one. Identify exactly where the dashboard gets wider than the viewport. Check the width of its toolbar, then inspect the minimum size and wrapping rules on each child. Try a wrapping flex row with consistent gaps. Run the same test and check all controls, since fixing one overflow can leave the last action below the dashboard unless the overall source order supports it.
Use transitions to show change while respecting motion settings
Choose one change where a transition makes the outcome clearer. A button can smoothly change border colour as it becomes active. A settings helper might briefly fade in when displayed. Limit each transition to named properties needed for the effect. Blanket transition-all rules can animate changes you did not intend and make debugging difficult. Use normal states that remain clear if transitions are disabled altogether.
A prefers-reduced-motion media query can remove movement for visitors who have indicated that preference. Keep every action usable after you remove the movement. The theme still changes. A pressed button still looks pressed. A question still expands. Avoid using motion to carry information that is missing from the text. When a browser allows you to emulate the reduced-motion setting, test both modes with the same sequence of interactions.
.workshop-action {
transition: background-color 160ms ease, border-color 160ms ease;
}
.workshop-action:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 3px;
}
@media (prefers-reduced-motion: reduce) {
.workshop-action {
transition: none;
}
}
Debug a change that seems to lag
Click Save, immediately click again and observe the label and style. Inspect the attribute to tell whether the script updated state immediately. If the state is correct while the style seems slow, examine the transition property and duration. If the attribute changes late, inspect the event handler. Fix the responsible layer and retest with reduction enabled. A program that works only if an animation finishes can fail when preferences or interruptions prevent the animation from running as expected.
Test open, selected, error and empty states
Write examples for more than the sunny-day page. Load three workshops and then load an empty collection. Open an information panel while focus is on its summary and confirm controls remain keyboard usable. Save one workshop, switch the filter, and return to the original topic. Verify whether the saved state remains as you designed. Clear persistence and check that the starting interface still works. Record which states you can recreate and the signal the visitor receives.
Run a six-case test before adding an enhancement
- Use the default system setting and inspect text, labels and focus indicators.
- Explicitly turn on the opposite theme and reread the same controls. Reset to System and confirm it follows the device setting again.
- Save one workshop using only the keyboard. Verify its pressed state and the visible confirmation.
- Activate a filter with no matching items and locate a way to reset it.
- Open a long information panel at a narrow width and confirm the rest of the content remains inside the page.
- Enable reduced motion and repeat one toggle and one disclosure action.
Inspect style evaluation step by step
For a card that does not look selected, inspect the button's actual attribute, then verify whether the CSS selector matches, then inspect which declarations win. A wrong attribute value, a selector written against the wrong element and an overridden style can produce the same screenshot. Change one thing at a time to identify the cause. Capture a short before-and-after note that explains whether your repair changed the state, the selector or the resulting value.
Build the light and dark dashboard project
Your portfolio project is a small workshop dashboard that can support both a keyboard-only visitor and someone on a narrow phone. Include a labelled theme control, a three-card agenda, a save action, a helpful empty state and one details area. Make card examples fictional. Give the visitor a useful sequence to follow, such as finding the first coding session, saving it and opening its equipment list. Check that the same sequence works under both colour schemes.
- Make the base HTML work, with readable headings, navigation and controls.
- Add reusable custom properties for colours, spacing and focus.
- Add a theme override and test System, Light and Dark with the same content.
- Express saved and open states using appropriate attributes and visible cues.
- Add a narrowly scoped transition and test behaviour under reduced motion.
- Record screenshots and an interaction test log, and explain which state owns each CSS rule.
Extend the project with a themeable widget
Copy the agenda to a page with its own surrounding theme. Give the embedded card group a scoped token override. Check the rest of the page does not change. Pick one property that should always stay consistent, such as focus thickness, and one that the new host should control, such as the card surface. This gives you a useful portfolio story about reusable components and shows why well-chosen scopes matter when a design is used in more than one place.
Prepare to explain an interface state in an interview
Walk through one action in your project with the inspector open. Name the starting state, trigger the change and show the affected element and its stylesheet rule. Explain how you tested it without a mouse and how the same flow behaves after a theme switch. Keep a small side-by-side example where changing a root-level token updates all relevant surfaces. Bring an example of a local override that changes only one card group so you can explain the difference.
- How does a reusable theme token get its final value? Describe inheritance, a default and an override, then show the computed value.
- How do you make a toggle understandable in the dark theme? Mention the accessible state, a visible indicator and a contrast check.
- How does the dashboard respect reduced motion? Explain which rule changes and show that the action still works when movement is removed.
- What would you inspect if a selected card still looks normal? Follow the actual attribute, matched selector, cascade and focus indicators.
- When would you use a media query rather than a custom attribute? Contrast an available-width change with a deliberate user choice that belongs to the interaction state.
Questions to answer before your first practice session
What should I know before I start?
Be comfortable using CSS selectors and reading the box model. Know how to use Flexbox or Grid for a small layout. Familiarity with JavaScript events helps when the project needs a theme button or a saved state. Try changing a class in developer tools so you can predict what a selector will match before writing a full handler.
Can I build a visible theme preference without a framework?
Yes. A small document can use custom properties, a media query and a short script that reflects an explicit choice on the root element. Practise the same workflow in plain HTML, CSS and JavaScript so you can explain where the theme decision comes from. A later framework may provide conveniences, but the browser still applies the final CSS rules.
How much time should I spend on visual polish?
Test readability and all interaction states before adding decorative effects. For a practice session, fix one meaningful issue like text contrast after toggling theme or clipped focus on a narrow layout. If you bring your practice dashboard to class in Ambala, include the saved test case so a trainer can reproduce the issue on a different screen or browser.
Work a component through four real revisions
A fictional Ambala training event has two workshop locations in one building. Your component is the announcement tile for each room, embedded first in a wide page and later inside a narrow sidebar. It contains a workshop title, room code, time, a registration status and a button. Make one workshop open, one full and one upcoming. This exercise gives you concrete states to inspect and a second layout setting in which the component still needs to make sense.
Revision one. Express an identifiable status
Keep the text information visible in every tile. Make the word “Full” prominent with a consistent border or token and add a line explaining what a visitor can do next, such as choosing a different sample session. For an upcoming session, show the date when registration opens. Check whether the style depends on the wording itself. Give the wrapper a defined state such as data-status with documented values. An editor could change the visible wording without breaking the selector. Inspect an invalid or missing value and ensure the default remains readable.
Revision two. Adjust the card to the space it occupies
Display the same card in two regions of one wide page. In one region, the tile can afford side-by-side metadata and action. In the sidebar there is room for only one usable column. A viewport condition would apply the same rule to both because both sit in the same viewport. Start by using a wrapping row with an appropriate minimum. As an optional experiment, set container-type to inline-size on the wrapper and use a container query to enhance its descendants when the wrapper is wide enough. Keep the narrow base working even when an enhancement is unavailable.
Revision three. Make the theme override local
A partner college wants the embedded tile to use a different highlight. Scope a change to the tile's wrapper while sharing the same focus, spacing and status styles. Test a highlighted tile beside an ordinary tile. Inspect the custom property values at both elements. If a selector points at the root by mistake, you can see the partner theme spread beyond the widget. Fix the scope and verify light and dark themes again. Give each status badge enough contrast on the adjusted background.
Revision four. Make spacing and zoom part of acceptance
Add a longer title and a longer room name. Try it with zoom and increased system text size. The status and action must remain visible below the content. If the card height was set in pixels, the text may spill out at a particular size. Replace a fragile fixed height with content-based sizing. Keep transitions limited to colour or other effects whose usefulness remains clear in reduced-motion mode. Retest the component when someone opens an information section, then switches theme while it is open. The visual theme should change without collapsing that content.
Demonstrate the final component with meaningful evidence
Save examples for open, full and upcoming. Include one screenshot that shows the same component in narrow and wide containers on the same page. Give a reviewer the controls to switch themes and enlarge the text so they can check your work directly. Explain how the component knows its own status, which values come from the surrounding theme, and why shrinking its available region affects its layout. A short explanation of these boundaries is more useful in an interview than a long list of CSS features.
Build a debugging note for a handoff
Document the current theme selection rule, where data attributes are set and which components can override tokens. Describe what a reader should see in the System, Light and Dark modes. Include the expected fallback with JavaScript unavailable. Add one known issue from development, how you reproduced it, and the exact fix. For example, “Upcoming badge stayed white after theme switch because its component had a fixed background; I replaced it with the surface token and checked both schemes.” This note gives someone else a useful starting point.
When a revision involves a breakpoint, record the actual content that forced the change. When it involves contrast, record the colours you measured and which size of text they apply to. When it involves a state selector, name the keyboard action you performed and the declared state you inspected. Replace opinions such as “looks better” with observations that can be repeated. Your finished dashboard should be easy to reopen weeks later and prove that a change is still doing its job.
Check a style when the state belongs to another control
Build two details panels, each with its own workshop information and a short list of equipment. Give a small “Current session” indicator to the selected item without hiding its title. Inspect what happens when one panel opens and another card is already saved. State can overlap, so the style for one condition should avoid overriding the cue for another. For example, the background may indicate the current day while a clearly labelled button communicates that a session was saved. Test in both colour schemes and with focus on the selected action.
For an advanced experiment, apply emphasis to a parent when it contains a pressed button using a selector whose subject is the parent. If the project's supported browsers require a fallback, keep the primary pressed indicator on the button and treat parent emphasis as optional. Do not put information in the decorative rule alone. Use a real browser to verify both the common state and the case where the parent enhancement is missing. Keep workshop information understandable with neither JavaScript nor transitions.
Verify a theme when the page is printed
Print preview the workshop dashboard with dark mode selected. A student who wants the time and room on paper still needs those details legible. Check how the browser prints backgrounds and text in its default settings. If the contrast or layout is poor, use a print style to simplify the surface and keep session information legible. Hide purely interactive controls that have no paper equivalent and retain the status as text. Test print preview in both modes. Add a note documenting which theme choices follow the system and which outputs have their own stylesheet rules.