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

MUI5中如何使用Emotion Styled组件为Button设置margin-right

解决MUI5中通过@emotion/styled给Button设置margin-right的问题

你原代码存在两个关键问题:

  • margin: '0, 3%, 0, auto' 写法错误,CSS margin值需用空格分隔,应改为 margin: '0 3% 0 auto'
  • .button 选择器无效,MUI Button组件默认不会生成该类名,需用正确的选择方式。

以下是几种可行的解决方案:

方案一:使用MUI内置Button类名选择

直接通过MUI Button的根类名MuiButton-root选中子元素:

const Wrapper = styled(Box)({
  display: 'flex',
  margin: '0 3% 0 auto',
  '& .MuiButton-root': {
    marginRight: '40px',
  },
});

方案二:给Button添加自定义类名

给目标Button添加自定义类名,再在Wrapper中选中:

const Wrapper = styled(Box)({
  display: 'flex',
  margin: '0 3% 0 auto',
  '& .custom-login-button': {
    marginRight: '40px',
  },
});

// 组件使用
<Wrapper>
  <Button variant='contained' className="custom-login-button">Login</Button>
  <Typography>Become a Seller</Typography>
  <Typography>More</Typography>
</Wrapper>

方案三:直接封装Styled Button

如果仅需给该Button设置样式,可直接用styled封装Button组件:

const StyledLoginButton = styled(Button)({
  marginRight: '40px',
});

const Wrapper = styled(Box)({
  display: 'flex',
  margin: '0 3% 0 auto',
});

// 组件使用
<Wrapper>
  <StyledLoginButton variant='contained'>Login</StyledButton>
  <Typography>Become a Seller</Typography>
  <Typography>More</Typography>
</Wrapper>

方案四:使用MUI sx属性(更简洁)

无需额外封装样式,直接给Button添加sx属性设置样式:

const Wrapper = styled(Box)({
  display: 'flex',
  margin: '0 3% 0 auto',
});

// 组件使用
<Wrapper>
  <Button variant='contained' sx={{ marginRight: '40px' }}>Login</Button>
  <Typography>Become a Seller</Typography>
  <Typography>More</Typography>
</Wrapper>

内容的提问来源于stack exchange,提问作者Krishnadev. V

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 07:20:33