3.0 KiB
3.0 KiB
Force Dark Mode via CSS Overrides
When to Use
The user wants the site to always look like dark mode regardless of:
- The
.darkclass being toggled on/off - The
prefers-color-schemesystem setting - The dark mode toggle switch being flipped
Approach
Instead of editing every dark: Tailwind variant across all pages (fragile, tedious), use CSS !important overrides in a shared stylesheet (e.g., style.css). These override the light-mode base classes so they render with dark-mode colors.
The Override Block
/* Force dark mode colors regardless of .dark class */
body {
background: #111827 !important;
color: #e5e7eb !important;
}
/* Common background classes — map to dark slate */
.bg-white { background-color: #1f2937 !important; }
[class*="bg-white "] { background-color: #1f2937 !important; }
[class*="bg-white/"] { background-color: rgba(31, 41, 55, 0.8) !important; }
.bg-gray-50 { background-color: #111827 !important; }
.bg-gray-100 { background-color: #1f2937 !important; }
/* Text colors — map to light text */
.text-gray-900 { color: #f9fafb !important; }
.text-gray-800 { color: #f3f4f6 !important; }
.text-gray-700 { color: #d1d5db !important; }
.text-gray-600 { color: #9ca3af !important; }
.text-gray-500 { color: #9ca3af !important; }
/* Border colors — map to dark borders */
.border-gray-200 { border-color: #374151 !important; }
.border-gray-100 { border-color: #374151 !important; }
/* Shadows — make them dark-ambient */
.shadow-lg, .shadow-xl, .shadow-md, .shadow-sm {
box-shadow: 0 1px 3px 0 rgba(0,0,0,0.3) !important;
}
/* Gradient backgrounds — used for page backgrounds */
[class*="from-gray-50"], [class*="to-gray-100"] {
background: #111827 !important;
}
/* Card-specific overrides */
.dashboard-card, .metric-card, .modern-card {
background: #1e293b !important;
border-color: #334155 !important;
}
Pitfalls
- Specificity issues — The
[class*="..."]attribute selectors may be needed to match compound classes likebg-white/10which contain/and don't match.bg-whitealone. - Inline styles — CSS with
!importantin the stylesheet still won't override inlinestyle="background: white"on the element. Those need to be edited at the HTML level. - Tailwind dynamic classes — If Tailwind JIT generates classes at runtime (e.g.,
bg-[#123456]), they bypass the override block. Use!importanton the specific selector. - Box shadows — Tailwind shadow utilities like
shadow-lguse color-specific box-shadows. The override block replaces them all with a single dark shadow, which may look slightly different than the original dark-mode shadows. - Backdrop filters — Elements with
backdrop-filter: blur(...)may still show through with unintended colors. Check these manually. - The toggle still functions — The
.darkclass can still be toggled on/off, it just won't produce visual changes anymore. If you want to fully disable the toggle, hide it withdisplay: noneor setpointer-events: none.