You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MUI 5中如何为div、span元素应用主题样式(非styled方案)

为原生HTML元素应用MUI主题的几种方案

不用把div/span转成styled组件,也不用legacy的makeStyles,这几个方法可以直接实现主题(明暗模式)适配:

1. 直接给原生元素用sx属性

MUI v5+的sx属性并非MUI组件专属,原生HTML元素也能直接使用。它支持访问主题变量,自动响应明暗模式切换,写法和MUI组件一致:

<div
  sx={{
    backgroundColor: (theme) => theme.palette.background.default,
    color: (theme) => theme.palette.text.primary,
    padding: 2, // 等价于theme.spacing(2)
    '&:hover': {
      backgroundColor: (theme) => theme.palette.action.hover
    }
  }}
>
  原生div跟随主题切换样式
</div>

sx属性基于Emotion,支持伪类、媒体查询等复杂样式,是最推荐的方案。

2. 用useTheme钩子配合内联样式

如果偏好内联样式,可以通过useTheme获取当前主题对象,直接给原生元素绑定样式:

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

function MyComponent() {
  const theme = useTheme();
  return (
    <div
      style={{
        backgroundColor: theme.palette.background.default,
        color: theme.palette.text.primary,
        padding: theme.spacing(2)
      }}
    >
      用useTheme控制原生元素样式
    </div>
  );
}

注意:内联样式不支持伪类、媒体查询,仅适合简单样式场景。

3. 全局CSS配合主题变量

如果需要给大量原生元素复用样式,可以在主题中定义全局CSS变量,再通过普通className引用:

步骤1:在主题中注入CSS变量

import { createTheme, ThemeProvider } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';

const theme = createTheme({
  // 定义明暗模式的调色板
  palette: {
    mode: 'light',
    background: {
      default: '#f5f5f5',
      paper: '#fff'
    },
    text: {
      primary: '#212121'
    }
  },
  components: {
    MuiCssBaseline: {
      styleOverrides: {
        ':root': {
          '--bg-default': (theme) => theme.palette.background.default,
          '--text-primary': (theme) => theme.palette.text.primary,
          '--spacing-2': (theme) => theme.spacing(2)
        }
      }
    }
  }
});

// 包裹应用
function App() {
  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      {/* 你的组件 */}
    </ThemeProvider>
  );
}

步骤2:在全局CSS中使用变量

.custom-native-element {
  background-color: var(--bg-default);
  color: var(--text-primary);
  padding: var(--spacing-2);
}

步骤3:给原生元素加className

<div className="custom-native-element">全局样式适配主题</div>

切换明暗模式时,主题变量会自动更新,对应的原生元素样式也会同步变化。

内容的提问来源于stack exchange,提问作者Dejavu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 10:22:25