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

MUI v5中能否在styled()内实现响应式布局?

在MUI的styled()中使用响应式断点的方法

可以在MUI的styled()方法中直接使用xs、sm、md这类响应式断点,完全不需要把样式拆分到内联sx属性里,以下是两种可行的实现方式:

方式1:通过媒体查询手动定义断点样式

利用主题提供的breakpoints.up()方法生成对应断点的媒体查询,写法直观且兼容性好:

import { Button } from "@mui/material";
import { styled } from "@mui/system";

const MyButton = styled(Button)(({ theme }) => ({
  // xs断点及以下的默认样式
  width: "10vw",
  // sm断点及以上生效
  [theme.breakpoints.up('sm')]: {
    width: "25vw"
  },
  // md断点及以上生效
  [theme.breakpoints.up('md')]: {
    width: "35vw"
  },
  // 按需添加lg、xl断点的样式
}));

export const Example = () => {
  return <MyButton>Test</MyButton>;
};

方式2:直接使用断点对象(类似sx语法)

@mui/system的styled()支持直接传入sx风格的断点对象,内部会自动转换为媒体查询。如果直接写对象不生效,可通过theme.breakpoints.resolveValues()处理:

import { Button } from "@mui/material";
import { styled } from "@mui/system";

const MyButton = styled(Button)(({ theme }) => ({
  width: theme.breakpoints.resolveValues({
    xs: "10vw",
    sm: "25vw",
    md: "35vw",
    lg: "45vw",
    xl: "55vw"
  })
}));

// 部分新版本MUI可直接省略resolveValues,简化为:
// const MyButton = styled(Button)({
//   width: {
//     xs: "10vw",
//     sm: "25vw",
//     md: "35vw"
//   }
// });

export const Example = () => {
  return <MyButton>Test</MyButton>;
};

两种方式都能让你把所有样式集中在styled()中定义,无需拆分到内联样式里。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 06:42:47