createVar
Creates a single scoped CSS Variable reference.
accent.css.ts
import { createVar, style } from '@vanilla-extract/css';
export const accentVar = createVar();CSS
No CSS created
As you can see, no CSS is generated when you create a variable, it is only a reference that can be set later on.
Setting the variable
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'
}
});CSS
.accent_blue__bbc7211 {
--accentVar__bbc7210: blue;
}
.accent_pink__bbc7212 {
--accentVar__bbc7210: 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'
}
}
}
});CSS
.accent_blue__9mlet01 {
--accentVar__9mlet00: blue;
}
.accent_pink__9mlet02 {
--accentVar__9mlet00: pink;
}
@media (prefers-color-scheme: dark) {
.accent_blue__9mlet01 {
--accentVar__9mlet00: lightblue;
}
.accent_pink__9mlet02 {
--accentVar__9mlet00: lightpink;
}
}Using the variable
The variable reference can then be passed as the value for any CSS property.
import { createVar, style } from '@vanilla-extract/css';
import { accentVar } from './accent.css.ts';
export const accentText = style({
color: accentVar
});CSS
.style_accentText__e25b7s0 {
color: var(--accentVar__kdc8w0);
}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
.accent_blue__kdc8w1 {
--accentVar__kdc8w0: blue;
}
.accent_pink__kdc8w2 {
--accentVar__kdc8w0: pink;
}Assigning variables dynamically
CSS variables can also be assigned dynamically using APIs in the @vanilla-extract/dynamic package.
@property rules
@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'
}
});CSS
@property --accentVar__1jl9ale0 {
syntax: "<color>";
inherits: false;
initial-value: blue;
}
.accent_pink__1jl9ale1 {
--accentVar__1jl9ale0: pink;
}