By : admin
Language: css
Date Published: 4 days, 3 hours ago
Dark mode improves readability in low‑light environments and reduces eye strain, making it a valued feature in financial dashboards, e‑commerce sites, and support portals. The most maintainable approach uses CSS custom properties (variables) to define color values and a class toggle on the <html> or <body> element to switch themes. By defining light and dark palettes as variables, you avoid duplicating styles and keep the CSS concise. Pair this with a prefers‑color‑scheme media query to respect the user’s system setting on first visit, and persist the choice in localStorage so the preference survives reloads. This method works with any CSS methodology—plain CSS, CSS modules, or CSS‑in‑JS—and requires minimal JavaScript to toggle the class and store the choice. It also integrates smoothly with accessibility tools, as you can ensure sufficient contrast in both palettes. Treating theming as a design‑system concern keeps component code clean and makes future theme adjustments (e.g., adding a high‑contrast mode) straightforward.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | /* styles.css – define colors as CSS variables */ :root { /* Light theme (default) */ --bg-primary: #ffffff; --bg-secondary: #f8fafc; --text-primary: #111827; --text-secondary: #6b7280; --accent: #2563eb; } /* Dark theme – applied when .dark class is on root */ .dark { --bg-primary: #111827; --bg-secondary: #1f2937; --text-primary: #f9fafb; --text-secondary: #d1d5db; --accent: #3b82f6; } /* Use variables throughout your styles */ body { background: var(--bg-primary); color: var(--text-primary); transition: background 0.2s, color 0.2s; } .container { background: var(--bg-secondary); border: 1px solid var(--text-secondary); } .button { background: var(--accent); color: white; border: none; padding: 0.5rem 1rem; border-radius: 0.375rem; } .button:hover { background: var(--accent); opacity: 0.9; } /* Optional: respect system preference on first load */ @media (prefers-color-scheme: dark) { :root:not(.dark) { --bg-primary: #111827; --bg-secondary: #1f2937; --text-primary: #f9fafb; --text-secondary: #d1d5db; --accent: #3b82f6; } } |