site/docs/api/create-var.md
Creates a single scoped CSS Variable reference.
// accent.css.ts
import { createVar, style } from '@vanilla-extract/css';
export const accentVar = createVar();
As you can see, no CSS is generated when you create a variable, it is only a reference that can be set later on.
The variable reference created above can be set using the “vars” key.
// accent.css.ts
import { createVar, style } from '@vanilla-extract/css';
export const accentVar = createVar();
export const blue = style({
vars: {
[accentVar]: 'blue'
}
});
export const pink = style({
vars: {
[accentVar]: 'pink'
}
});
Keep in mind the value of the variable can be changed in another class or even in a media query. For example, let’s change the value when the user prefers a dark color-scheme:
// accent.css.ts
import { createVar, style } from '@vanilla-extract/css';
export const accentVar = createVar();
export const blue = style({
vars: {
[accentVar]: 'blue'
},
'@media': {
'(prefers-color-scheme: dark)': {
vars: {
[accentVar]: 'lightblue'
}
}
}
});
export const pink = style({
vars: {
[accentVar]: 'pink'
},
'@media': {
'(prefers-color-scheme: dark)': {
vars: {
[accentVar]: 'lightpink'
}
}
}
});
The variable reference can then be passed as the value for any CSS property.
// style.css.ts
import { createVar, style } from '@vanilla-extract/css';
import { accentVar } from './accent.css.ts';
export const accentText = style({
color: accentVar
});
// accent.css.ts
import { createVar, style } from '@vanilla-extract/css';
export const accentVar = createVar();
export const blue = style({
vars: {
[accentVar]: 'blue'
}
});
export const pink = style({
vars: {
[accentVar]: 'pink'
}
});
CSS variables can also be assigned dynamically using APIs in the @vanilla-extract/dynamic package.
@property rules can also be created using createVar.
CSS variables with @property rules are used in the same way as regular CSS variables:
// accent.css.ts
import { createVar, style } from '@vanilla-extract/css';
export const accentVar = createVar({
syntax: '<color>',
inherits: false,
initialValue: 'blue'
});
export const pink = style({
vars: {
[accentVar]: 'pink'
}
});