CSS 变量
在 Chakra UI 中使用可感知 token 的 CSS 变量
概述
¥Overview
CSS 变量已成为在 Web 上创建共享值的实际方法。它对于避免属性插值、类名重新生成以及减少 token 值的运行时求值非常有用。
¥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.
示例
¥Examples
基础
¥Basic
使用 css
属性创建 CSS 变量
¥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>
访问令牌
¥Access tokens
使用完整的 token 路径访问 token
¥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>
响应式样式
¥Responsive Styles
使用响应式语法使 CSS 变量具有响应式功能
¥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>
颜色不透明度修改器
¥Color Opacity Modifier
访问颜色标记时,可以使用 opacity 修饰符来访问具有不透明度的颜色。要求使用 {}
语法。
¥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>
虚拟颜色
¥Virtual Color
变量可以通过 colors.colorPalette.*
值指向虚拟颜色。这对于创建主题组件非常有用。
¥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>