CSS Variables
Using token-aware CSS variables in Chakra UI
CSS variables have become the defacto way to create shared values on the web. It's very useful to avoid prop interpolations, classname regeneration, and reduce runtime evaluation of token values.
Use the css
prop to create css variables
<Box css={{ "--font-size": "18px" }}>
<h3 style={{ fontSize: "calc(var(--font-size) * 2)" }}>Hello</h3>
<p style={{ fontSize: "var(--font-size)" }}>Hello</p>
</Box>
Use the full token path to access tokens
<Box css={{ "--color": "colors.red.500" }}>
<p style={{ color: "var(--color)" }}>Hello</p>
</Box>
Here's an example of how to access size tokens
<Box css={{ "--size": "sizes.10" }}>
<p style={{ width: "var(--size)", height: "var(--size)" }}>Hello</p>
</Box>
Use the responsive syntax to make css variables responsive
<Box css={{ "--font-size": { base: "18px", lg: "24px" } }}>
<h3 style={{ fontSize: "calc(var(--font-size) * 2)" }}>Hello</h3>
<p style={{ fontSize: "var(--font-size)" }}>Hello</p>
</Box>
When accessing color tokens, you can use the opacity modifier to access the
color with an opacity. The requirement is to use the {}
syntax.
<Box css={{ "--color": "{colors.red.500/40}" }}>
<p style={{ color: "var(--color)" }}>Hello</p>
</Box>
Variables can point to a virtual color via the colors.colorPalette.*
value.
This is useful for creating theme components.
<Box colorPalette="blue" css={{ "--color": "colors.colorPalette.400" }}>
<p style={{ color: "var(--color)" }}>Hello</p>
</Box>