如何为所有Material-UI组件添加填充和边距?

98

我需要向一些Material-UI组件添加填充或边距,但找不到简单易行的方法。我能否将这些属性添加到所有组件中?类似于以下方式:

<Button color="default" padding={10} margin={5}>

我知道使用纯CSS和类也可以实现这一点,但我想以Material-UI的方式完成。

9个回答

107
您可以通过先导入组件,然后在 BOX 组件中使用“Spacing”来实现间距:

您可以通过先导入组件,然后在 BOX 组件中使用“间隔”来实现间距:

import Box from '@material-ui/core/Box';

Box组件作为要"修改"间距的组件的"包装器"。

然后,您可以在组件上使用以下属性:

space实用程序将简写的margin和padding props转换为margin和padding CSS声明。这些props的名称采用{property}{sides}格式命名。

其中property之一是:

m-设置margin的类 p-设置padding的类

sides之一是:

t-设置margin-top或padding-top的类

b-设置margin-bottom或padding-bottom的类

l-设置margin-left或padding-left的类

r-设置margin-right或padding-right的类

x-设置左右的类

y-设置上下的类

空格-在元素的4个边上设置margin或padding的类

例如:

<Box m={2} pt={3}>
  <Button color="default">
    Your Text
  </Button>
</Box>

7
对于那些对m={2}和pt={3}感到困惑的人,这些基本上是相对于主题中设置的间距的。例如,如果您有如下主题: const theme = { spacing: 8, } 那么m={2}会将所有边缘设置为82, pt={3}会将顶部填充设置为83。 - Farhan Haider
6
这意味着需要多次使用 Box 组件。这样做推荐吗? - oskrgg
2
@oskrgg:文档和其他各种资源都说,Box(没有任何component修饰)是div的简写。它试图将每个提供的属性映射到其div的相应CSS属性。这通常有助于将此类属性保留在“代码”空间中,而不是强制开发人员查找和更改样式、主题等。我认为这个特定的答案是一个推荐和适当的用法。总的来说,Box并不比添加一个div更糟糕。 - Tom Stambaugh
2
@TomStambaugh,也许提问者想要为“Button”添加真正的填充。将填充添加到“Box”组件包装器就像将边距添加到“Button”一样。 - NearHuscarl
1
@yaminoyuki 8px 可能是默认值 https://mui.com/customization/spacing/ - Farhan Haider
显示剩余4条评论

34
Material-UI的样式解决方案在4.x版本中使用JSS作为核心。它是一个高性能的JS到CSS编译器,可以在运行时和服务器端工作。
import { withStyles} from '@material-ui/core/styles';

const styles = theme => ({
  buttonPadding: {    
    padding: '30px',   
  },
});

function MyButtonComponent(props) {
  const { classes } = props;

  return (      
      <Button
        variant="contained"
        color="primary"
        className={classes.buttonPadding}
      >
        My Button
      </Button>
  );
}

export default withStyles(styles)(MyButtonComponent);

你可以使用 withStyle 高阶组件(HOC)将样式注入到你的组件中。这是它的工作原理,而且它非常优化。

编辑:要在所有组件上应用样式,你需要使用 createMuiTheme 并将你的组件包裹在 MuiThemeprovider 中。

const theme = createMuiTheme({
  overrides: {
    MuiButton: {
      root: {
        margin: "10px",
        padding: "10px"
      }
    }
  }
});

 <MuiThemeProvider theme={theme}>
  <Button variant="contained" color="primary">
    Custom CSS
  </Button>

  <Button variant="contained" color="primary">
    MuiThemeProvider
  </Button>

  <Button variant="contained" color="primary">
    Bootstrap
  </Button>
</MuiThemeProvider>

4
可以为特定组件工作,但如何为所有 MUI 组件声明这些 props? - rostamiani
2
我不想给所有组件添加填充和边距。我需要为每个组件自定义添加这些属性。 - rostamiani
2
我可以将这些属性添加到所有组件中吗? 这是您的问题声明。 - Sakhi Mansoor
为什么不给所有组件提供样式属性并进行内联样式呢?但我不建议您为每个组件声明JSS,以利用JSS在运行时编译CSS并注入到我们的组件中的强大功能。 - Sakhi Mansoor
7
MuiButton 引用是来自 Material-UI 框架的 API。与其使用 Button 的原因是为了避免与其他库或项目中的组件名称冲突。 - oligofren
显示剩余8条评论

14

在Material-UI v5中,可以使用sx属性更改按钮样式。您可以在这里查看边距/填充系统属性及其对应的CSS属性。

<Button sx={{ m: 2 }} variant="contained">
  margin
</Button>
<Button sx={{ p: 2 }} variant="contained">
  padding
</Button>
<Button sx={{ pt: 2 }} variant="contained">
  padding top
</Button>
<Button sx={{ px: 2 }} variant="contained">
  padding left, right
</Button>
<Button sx={{ my: 2 }} variant="contained">
  margin top, bottom
</Button>

如果您想快速原型化组件,则可以省略像 mp 这样的属性简写,如果您希望代码更易于阅读,可以使用常规的CSS属性。

下面的代码等效于上述代码,但使用了CSS属性:

<Button sx={{ margin: 2 }} variant="contained">
  margin
</Button>
<Button sx={{ padding: 2 }} variant="contained">
  padding
</Button>
<Button sx={{ paddingTop: 2 }} variant="contained">
  padding top
</Button>
<Button sx={{ paddingLeft: 3, paddingRight: 3 }} variant="contained">
  padding left, right
</Button>
<Button sx={{ marginTop: 2, marginBottom: 2 }} variant="contained">
  margin top, bottom
</Button>

在线演示

编辑52124938/如何为所有Material UI组件添加填充和边距


使用 sx 还是 m* 和 p* 的 sysProps 来进行填充和边距有什么优缺点? - Seth McClaine

7
import Box from '@material-ui/core/Box';

<Box m={1} p={2}>
  <Button color="default">
    Your Text
  </Button>
</Box>

21
请勿只发布代码作为答案,还需解释代码的作用及如何解决问题。带有解释的答案通常质量更高且更容易获得赞同。 - Suraj Kumar

1
我们可以使用material-ui的makeStyles来实现这一点,而不需要使用Box组件。
创建一个名为customSpacing的函数,如下所示。

customSpacing.js

import { makeStyles } from "@material-ui/core";

const spacingMap = {
  t: "Top", //marginTop
  b: "Bottom",//marginBottom
  l: "Left",//marginLeft
  r: "Right",//marginRight
  a: "", //margin (all around)
};

const Margin = (d, x) => {
  const useStyles = makeStyles(() => ({
    margin: () => {
      // margin in x-axis(left/right both)
      if (d === "x") {
        return {
          marginLeft: `${x}px`,
          marginRight: `${x}px`
        };
      }
      // margin in y-axis(top/bottom both)
      if (d === "y") {
        return {
          marginTop: `${x}px`,
          marginBottom: `${x}px`
        };
      }
      return { [`margin${spacingMap[d]}`]: `${x}px` };
    }
  }));
  const classes = useStyles();
  const { margin } = classes;
  return margin;
};

const Padding = (d, x) => {
  const useStyles = makeStyles(() => ({
    padding: () => {
      if (d === "x") {
        return {
          paddingLeft: `${x}px`,
          paddingRight: `${x}px`
        };
      }
      if (d === "y") {
        return {
          paddingTop: `${x}px`,
          paddingBottom: `${x}px`
        };
      }
      return { [`padding${spacingMap[d]}`]: `${x}px` };
    }
  }));
  const classes = useStyles();
  const { padding } = classes;
  return padding;
};

const customSpacing = () => {
  return {
    m: Margin,
    p: Padding
  };
};

export default customSpacing;

Now import above customSpacing function into your Component and use it like below. App.js

import React from "react";
import "./styles.css";
import customSpacing from "./customSpacing";

const App = () => {
  const { m, p } = customSpacing();
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2
        style={{ background: "red" }}
        className={`${m("x", 20)} ${p("x", 2)}`}
      >
        Start editing to see some magic happen!
      </h2>
    </div>
  );
};

export default App;

点击打开 CodeSandbox


0

特定于使用全局样式的"padding-top"(10px)

阅读此内容!

import React from "react";
import { Container, makeStyles, Typography } from "@material-ui/core";
import { Home } from "@material-ui/icons";

const useStyles = makeStyles((theme) => ({

container: {
    paddingTop: theme.spacing(10),
},
}));

const LeftBar = () => {
const classes = useStyles();

return (
    <Container className={classes.container}>
        <div className={classes.item}>
            <Home className={classes.icon} />
            <Typography className={classes.text}>Homepage</Typography>
        </div>
    </Container>
);
};

export default LeftBar;

enter image description here


0
<Button color="default" p=10px m='5px'>

请阅读如何撰写好的答案?。虽然这个代码块可能回答了OP的问题,但如果您解释一下这段代码与问题中的代码有何不同,您做出了哪些更改,为什么要更改以及为什么这样解决问题而不引入其他问题,那么这个答案将会更加有用。- 来自审核 - Saeed Zhiany

0

在版本4.0之前,我们可以在Typography组件上使用makeStyles或styles props来设置边距。

我强烈建议使用material ui的5.0版本,在这个版本中,Typography具有margin props,使生活更加轻松。


-2

首先在主题提供程序中设置初始间距,即包含您应用程序入口的标记。它应该看起来像这样

import { createMuiTheme } from '@material-ui/core/styles';
import purple from '@material-ui/core/colors/purple';
import green from '@material-ui/core/colors/green';

const theme = createMuiTheme({
  palette: {
    primary: {
      main: purple[500],
    },
    secondary: {
      main: green[500],
    },
  },
});
function App() {
  return (
      <ThemeProvider theme={theme}>
        <LandingPage />
      </ThemeProvider>
  );
 }

就是这样。所以将主题部分添加到代码中,并根据需要使用边距/填充。

const theme = {
  spacing: 8,
}

<Box m={-2} /> // margin: -16px;
<Box m={0} /> // margin: 0px;
<Box m={0.5} /> // margin: 4px;
<Box m={2} /> // margin: 16px;

你可以使用“margin”或“m”来表示边距,同样适用于内边距。
const theme = {
  spacing: value => value ** 2,
}

<Box m={0} /> // margin: 0px;
<Box m={2} /> // margin: 4px;

或者

<Box m="2rem" /> // margin: 2rem;
<Box mx="auto" /> // margin-left: auto; margin-right: auto

如何为<Grid/>允许边距? - Harsh Phoujdar
1
这并没有回答问题。Box组件默认具有padding和margin属性。问题是如何将这些属性添加到其他组件(例如Button)。 - DollarAkshay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接