跳到主要內容
+

sx 屬性

sx 屬性是用於定義可存取主題的自訂樣式的快捷方式。

sx 屬性讓您可以使用 CSS 的超集,其中封裝了 @mui/system 中公開的所有樣式函數。您可以使用此屬性指定任何有效的 CSS,以及許多 MUI System 獨有的主題感知屬性。

基本範例

以下演示說明如何使用 sx 屬性。請注意,並非所有值都是有效的 CSS 屬性——這是因為 sx 鍵會對應到主題的特定屬性。本文檔的其餘部分將更詳細地探討這個概念。

工作階段
98.3 K
+18.77%
與上週相比
按下 Enter 開始編輯

主題感知屬性

邊框

border 屬性只能接收數字作為值。它會使用該數字建立實心黑色邊框,以定義像素寬度

<Box sx={{ border: 1 }} />
// equivalent to border: '1px solid black'

borderColor 屬性可以接收字串,表示 theme.palette 中的路徑

<Box sx={{ borderColor: 'primary.main' }} />
// equivalent to borderColor: theme => theme.palette.primary.main

borderRadius 屬性會將其接收的值乘以 theme.shape.borderRadius 值(此值的預設值為 4px)。

<Box sx={{ borderRadius: 2 }} />
// equivalent to borderRadius: theme => 2 * theme.shape.borderRadius

請在邊框頁面上閱讀更多資訊。

顯示

displayPrint 屬性可讓您指定 CSS display 值,該值僅在列印時套用

<Box sx={{ displayPrint: 'none' }} /> // equivalent to '@media print': { display: 'none' }

請在顯示頁面上閱讀更多資訊。

網格

CSS Grid 屬性 gaprowGapcolumnGap 會將其接收的值乘以 theme.spacing 值(此值的預設值為 8px)。

<Box sx={{ gap: 2 }} />
// equivalent to gap: theme => theme.spacing(2)

請在網格頁面上閱讀更多資訊。

調色盤

colorbackgroundColor 屬性可以接收字串,表示 theme.palette 中的路徑

<Box sx={{ color: 'primary.main' }} />
// equivalent to color: theme => theme.palette.primary.main

backgroundColor 屬性也可以透過其別名 bgcolor 取得

<Box sx={{ bgcolor: 'primary.main' }} />
// equivalent to backgroundColor: theme => theme.palette.primary.main

請在調色盤頁面上閱讀更多資訊。

位置

zIndex 屬性會將其值對應到 theme.zIndex

<Box sx={{ zIndex: 'tooltip' }} />
// equivalent to zIndex: theme => theme.zIndex.tooltip

請在位置頁面上閱讀更多資訊。

陰影

boxShadow 屬性會將其值對應到 theme.shadows

<Box sx={{ boxShadow: 1 }} />
// equivalent to boxShadow: theme => theme.shadows[1]

請在陰影頁面上閱讀更多資訊。

尺寸

尺寸屬性 widthheightminHeightmaxHeightminWidthmaxWidth 對於值使用以下自訂轉換函數

function transform(value) {
  return value <= 1 && value !== 0 ? `${value * 100}%` : value;
}

如果值介於 (0, 1] 之間,則會將其轉換為百分比。否則,會直接在 CSS 屬性上設定

<Box sx={{ width: 1/2 }} /> // equivalent to width: '50%'
<Box sx={{ width: 20 }} /> // equivalent to width: '20px'

請在尺寸頁面上閱讀更多資訊。

間距

間距屬性 marginpadding 和對應的完整屬性會將其接收的值乘以 theme.spacing 值(此值的預設值為 8px

<Box sx={{ margin: 2 }} />
// equivalent to margin: theme => theme.spacing(2)

以下別名可用於間距屬性

Prop CSS 屬性
m margin
mt margin-top
mr margin-right
mb margin-bottom
ml margin-left
mx margin-leftmargin-right
my margin-topmargin-bottom
p padding
pt padding-top
pr padding-right
pb padding-bottom
pl padding-left
px padding-leftpadding-right
py padding-toppadding-bottom

請在間距頁面上閱讀更多資訊。

排版

fontFamilyfontSizefontStylefontWeight 屬性會將其值對應到 theme.typography

<Box sx={{ fontWeight: 'fontWeightLight' }} />
// equivalent to fontWeight: theme.typography.fontWeightLight

省略 CSS 屬性前綴 fontWeight 也可以達到相同的效果

<Box sx={{ fontWeight: 'light' }} />
// equivalent to fontWeight: theme.typography.fontWeightLight

還有一個額外的 typography 屬性可用,它會設定特定 theme.typography 變體中定義的所有值

<Box sx={{ typography: 'body1' }} />
// equivalent to { ...theme.typography.body1 }

請在排版頁面上閱讀更多資訊。

響應式值

sx 屬性關聯的所有屬性也支援特定斷點和容器查詢的響應式值。

請在用法頁面 - 響應式值上閱讀更多資訊。

回呼值

當您需要取得物件的主題值時,請使用回呼

<Box
  sx={(theme) => ({
    ...theme.typography.body,
    color: theme.palette.primary.main,
  })}
/>

在 TypeScript 中,若要將自訂主題屬性與 sx 屬性回呼搭配使用,請使用模組擴充,從 @mui/system 庫擴充 Theme 類型

import * as React from 'react';
import Box from '@mui/material/Box';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import { orange } from '@mui/material/colors';

declare module '@mui/system' {
  interface Theme {
    status: {
      warning: string;
    };
  }
}

const theme = createTheme({
  status: {
    warning: orange[500],
  },
});

export default function App() {
  return (
    <ThemeProvider theme={theme}>
      <Box
        sx={(theme) => ({
          bgcolor: theme.status.warning,
        })}
      >
        Example
      </Box>
    </ThemeProvider>
  );
}

陣列值

當您想要部分覆寫前一個索引中的某些樣式時,陣列類型很有用

<Box
  sx={[
    {
      '&:hover': {
        color: 'red',
        backgroundColor: 'white',
      },
    },
    foo && {
      '&:hover': { backgroundColor: 'grey' },
    },
    bar && {
      '&:hover': { backgroundColor: 'yellow' },
    },
  ]}
/>

當您將滑鼠懸停在此元素上時,會套用 color: red; backgroundColor: white;

如果 foo: true,則當懸停時會套用 color: red; backgroundColor: grey;

如果 bar: true,則無論 foo 值為何,當懸停時都會套用 color: red; backgroundColor: yellow;,因為陣列的較高索引具有較高的優先順序。

<Box
  sx={[
    { mr: 2, color: 'red' },
    (theme) => ({
      '&:hover': {
        color: theme.palette.primary.main,
      },
    }),
  ]}
/>

傳遞 sx 屬性

如果您想要從自訂元件接收 sx 屬性並將其向下傳遞到另一個 MUI System,我們建議使用此方法

  • 按下 Enter 開始編輯

    動態值

    對於高度動態的 CSS 值,我們建議使用內聯 CSS 變數,而不是在每次渲染時將具有不同值的物件傳遞給 sx 屬性。這種方法避免將不必要的 style 標籤插入到 DOM 中,這可以防止在處理可以容納各種頻繁變更的值的 CSS 屬性時,可能發生的效能問題——例如,具有即時預覽的顏色選擇器。

    TypeScript 用法

    sx 屬性常見的混淆來源是 TypeScript 的類型擴展,這會導致此範例無法如預期般運作

    const style = {
      flexDirection: 'column',
    };
    
    export default function App() {
      return <Button sx={style}>Example</Button>;
    }
    
    // Type '{ flexDirection: string; }' is not assignable to type 'SxProps<Theme> | undefined'
    // Type '{ flexDirection: string; }' is not assignable to type 'CSSSelectorObject<Theme>'
    //   Property 'flexDirection' is incompatible with index signature
    //     Type 'string' is not assignable to type 'SystemStyleObject<Theme>'
    

    問題在於 flexDirection 屬性的類型被推斷為 string,這太寬泛了。若要修正此問題,您可以將傳遞給 sx 屬性的物件/函數轉換為 const

    const style = {
      flexDirection: 'column',
    } as const;
    
    export default function App() {
      return <Button sx={style}>Example</Button>;
    }
    

    或者,您可以將樣式物件直接傳遞給 sx 屬性

    export default function App() {
      return <Button sx={{ flexDirection: 'column' }}>Example</Button>;
    }
    

    效能

    若要瞭解更多關於 sx 屬性的效能權衡,請查看用法 - 效能權衡