跳到主要內容
+

使用 CSS 變數

了解如何使用 CSS 變數來客製化 Joy UI 元件。

簡介

若要使用 CSS 變數,您必須使用 <CssVarsProvider /> 工具包裹您的應用程式。

import { CssVarsProvider } from '@mui/joy/styles';

function App() {
  return <CssVarsProvider>...</CssVarsProvider>;
}

接著您可以使用 theme.vars.* 標記法,根據 CSS 變數套用樣式。Joy UI 支援的所有樣式 API 都能使用此標記法,包含 styled() 函式和 sx prop。

樣式 API

在 Joy UI 支援的任何樣式 API 中使用 theme.vars.* 標記法

styled 函式

const Div = styled('div')(({ theme }) => ({
  // Outputs 'var(--joy-palette-primary-500)'
  color: theme.vars.palette.primary[500],
}));

sx prop

// Outputs 'var(--joy-shadow-sm)'
<Chip sx={(theme) => ({ boxShadow: theme.vars.shadow.sm })} />

您也可以使用簡寫語法,以與上述範例相同的方式解析 theme.vars.* 的值。

<Chip
  sx={{
    border: '1px solid',

    // For color properties, lookup from `theme.vars.palette`
    color: 'neutral.800', // 'var(--joy-palette-neutral-800)'
    borderColor: 'neutral.400', // 'var(--joy-palette-neutral-400)'

    // lookup from `theme.vars.shadow`
    shadow: 'sm', // 'var(--joy-shadow-sm)'

    // lookup from `theme.vars.fontSize`
    fontSize: 'sm', // 'var(--joy-fontSize-sm)'
  }}
/>

主題化的元件

extendTheme({
  components: {
    JoyButton: {
      root: ({ theme }) => ({
        // Outputs 'var(--joy-fontFamily-display)'
        fontFamily: theme.vars.fontFamily.display,
      }),
    },
  },
});

useTheme hook

import { useTheme } from '@mui/joy/styles';

const SomeComponent = () => {
  const theme = useTheme(); // The runtime theme.

  return (
    <div>
      <p style={{ color: {theme.vars.palette.primary[500]} }}>Some text here.</p>
    </div>
  );
};

建立新的變數

若要建立新的 CSS 變數,請使用原始主題值 (theme.* 而非 theme.vars.*)。以下程式碼範例說明如何建立新的陰影主題值

const Div = styled('div')(({ theme }) => ({
  // Note that it's using `theme.shadow`, not `theme.vars.shadow`
  boxShadow: theme.shadow.sm.replace(/,/g, ', inset'),
}));

調整色彩不透明度

使用自動產生的不透明度通道 tokens (mainChannellightChanneldarkChannel),搭配 rgba 色彩標記法,即可在 Joy UI 的所有可用調色盤中調整色彩不透明度。

const Div = styled('div')(({ theme }) => ({
  backgroundColor: `rgba(${theme.vars.palette.primary.mainChannel} / 0.2)`,
}));

自訂前綴

每個 Joy UI CSS 變數預設都會加上 joy 前綴。若要變更此前綴,請在 <CssVarsProvider /> 元件的 extendTheme 函式內使用 cssVarPrefix 屬性。

import { CssVarsProvider, extendTheme } from '@mui/joy/styles';

function App() {
  return (
    <CssVarsProvider theme={extendTheme({ cssVarPrefix: 'company' })}>
      ...
    </CssVarsProvider>
  );
}

接著產生的 CSS 變數將會是

- --joy-fontSize-md: 1rem;
+ --company-fontSize-md: 1rem;

移除預設前綴

cssVarPrefix 屬性中使用空值 ('') 即可從產生的 CSS 變數中移除預設的 joy 前綴

import { CssVarsProvider, extendTheme } from '@mui/joy/styles';

function App() {
  return (
    <CssVarsProvider theme={extendTheme({ cssVarPrefix: '' })}>...</CssVarsProvider>
  );
}
- --joy-fontSize-md: 1rem;
+ --fontSize-md: 1rem;