【问题标题】:How do you change Material UI Grid properties based on screen size?如何根据屏幕尺寸更改 Material UI Grid 属性?
【发布时间】:2021-11-28 18:50:46
【问题描述】:

我正在使用 Material UI,并且主页中有一个网格。无论屏幕大小如何,这个网格都有一些我想保留的属性。但是,当屏幕为lg(1200px)或更大时,我想添加负边距。

目前,网格看起来像

<Grid container spacing={0} direction="row" maxWidth="lg" margin="auto"> 

如果屏幕尺寸为 1200 像素或更大,我只想添加 margin-top="-50px。这样做的最佳方法是什么?

【问题讨论】:

    标签: css material-ui


    【解决方案1】:

    最好的做法是将样式与组件或元素分开,除非您只想更改一两件事。

    尝试使用 useStyles。它会让你的生活更轻松。

    为了更好地理解这里发生了什么,我在下面重新创建了您的网格。

    import { Grid} from "@material-ui/core";
    import React from "react";
    
        const YourComponent = () => {
          const classes = useStyles();
    
          return (
            <>
           <Grid className={classes.myGrid}>
           Your Content Goes Here
          </Grid>
            </>
          );
        };
        
        export default YourComponent;
    

    Material UI 已实现支持多种屏幕尺寸的断点。假设您为您的样式创建了另一个文件,如下所示:

          import { makeStyles } from "@material-ui/core/styles";
                
                export default makeStyles((theme) => ({
                  toolbar: theme.mixins.toolbar,
    
                  myGrid: {
        
            // here goes your margin for large screens and up
               [theme.breakpoints.up("lg")]: {
              margin: "-50px",
            },
           //here goes your regular size
        }
    }));
    

    不过,您应该谨慎使用负边距。我相信有更好的方法来重新创建您的视图。

    你一定要看看MUI's documentation on breakpoints

    【讨论】:

      【解决方案2】:

      你可以试试 MUI 的useMediaQuery

      const matches = useMediaQuery("(min-width:1200px)");
      

      <Grid
            container
            spacing={0}
            direction="row"
            maxWidth="lg"
            margin={matches ? "-50px auto auto" : "auto"}
      >
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-15
        • 1970-01-01
        • 2021-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-24
        • 2018-04-26
        相关资源
        最近更新 更多