P2.8: CSS Variables & Themes

CSS Variables (Custom Properties) allow you to store values and reuse them throughout stylesheets, enabling easy dark/light mode toggling.


1. Declaring CSS Variables

Variables are declared inside the :root pseudo-class and accessed using var().

:root {
  --primary-color: #39FF14;
  --bg-color: #060c18;
}

body {
  background-color: var(--bg-color);
  color: var(--primary-color);
}
Mark Dalgleish

Mark DalgleishView Profile 🔗

Real-World Developer Case Study
13 Years Exp
RoleCreator of CSS Modules
Salary₹88 Lakhs/yr equivalent
CompanyVercel
Core Tech Stack
CSS VariablesDark Mode theme tokensCSS Modules

Dynamic styling and theming used to require heavy JS computations. Now, CSS variables allow you to toggle themes on the client instantly with zero layout re-renders.


🎓 Practice Assignment Tasks

  • Define primary colors using CSS variables.
  • Build a basic card component styled with those variables.
  • Write a stylesheet override that changes those variable values when the page body has a `.dark` class.
Stuck? Hints available
/* Write your CSS styling rules here to complete the assignment */
🔒 Code requirements not met yet. Complete the tasks above.
🔒 Complete the Practice Assignment above to unlock completion.
Advertisement
NS
Ask Nextsem
AI Mode
NS
Home
Course
Playground