Theming And Variables
If you find yourself repeating color branches in multiple components, the problem is usually design tokens, not missing runtime logic.
Define variables in config
ts
import { defineEngineConfig } from '@pikacss/core'
export default defineEngineConfig({
variables: {
variables: {
// Simple variable (rendered under :root by default)
'--color-bg': '#ffffff',
'--color-text': '#1a1a1a',
// Variable with null value (autocomplete only, no CSS output)
'--external-var': null,
// Scoped variables under a selector
'[data-theme="dark"]': {
'--color-bg': '#1a1a1a',
'--color-text': '#ffffff',
},
// Variable with advanced options
'--spacing-unit': {
value: '4px',
autocomplete: {
asValueOf: ['margin', 'padding', 'gap'],
asProperty: true,
},
pruneUnused: false, // Always include in output
},
},
// Whether to remove unused variables from the final CSS
pruneUnused: true,
// Variables that are always included regardless of usage
safeList: ['--color-bg', '--color-text'],
},
})You can scope variable definitions under selectors to create theme-specific values.
ts
import { defineEngineConfig } from '@pikacss/core'
export default defineEngineConfig({
variables: {
variables: {
// Base token — not referenced directly in any atomic style
'--spacing-base': '4px',
// Derived token — references --spacing-base in its value
'--spacing-lg': 'calc(var(--spacing-base) * 4)',
},
pruneUnused: true,
// --spacing-base is not in safeList and is never used in pika() calls directly.
// But because --spacing-lg (which IS used) references it via var(),
// the BFS expansion ensures --spacing-base is also kept in the CSS output.
},
})Use variables in components
ts
const className = pika({
color: 'var(--color-text)',
backgroundColor: 'var(--color-bg)',
})css
/* Preflight: variable declarations */
:root {
--color-primary: #0ea5e9;
--color-bg: #ffffff;
--color-text: #1e293b;
}
[data-theme="dark"] {
--color-bg: #0f172a;
--color-text: #e2e8f0;
}
/* Atomic styles generated by pika() */
.pk-a { color: var(--color-text); }
.pk-b { background-color: var(--color-bg); }If the variable value has to change per instance at runtime, see Dynamic Values With CSS Variables.
A practical theming strategy
- Use selectors to describe theme context such as light or dark.
- Use variables to carry the actual token values.
- Keep component style definitions focused on semantic token usage.
That separation is easier to maintain than duplicating full dark and light component objects.
Do and do not
| Do | Do not |
|---|---|
| Store theme values in CSS variables. | Duplicate entire components for each theme without reason. |
| Scope variable definitions with selectors. | Put theme logic into runtime object construction. |
| Keep component objects semantic. | Hardcode every token in every component. |