Below is an example showing two ways of specifying media queries within makeStyles
(further down is a v5 example using styled
). You can use up
, down
, only
, and between
functions in theme.breakpoints (which generate the media query strings for you based on the breakpoints specified in the theme), or you can use media queries directly.
import React from "react";
import Button from "@material-ui/core/Button";
import { makeStyles } from "@material-ui/core/styles";
const useStyles = makeStyles(theme => ({
button: {
color: "white",
[theme.breakpoints.down("xs")]: {
marginTop: theme.spacing(1),
backgroundColor: "purple"
},
[theme.breakpoints.between("sm", "md")]: {
marginTop: theme.spacing(3),
backgroundColor: "blue"
},
"@media (min-width: 1280px)": {
marginTop: theme.spacing(5),
backgroundColor: "red"
}
}
}));
export default function App() {
const classes = useStyles();
return (
<Button className={classes.button} variant="contained">
Hello World!
</Button>
);
}
Related documentation:
Below is a similar example using v5 of Material-UI. This has been adjusted to use styled
instead of makeStyles
and the usage of theme.breakpoints.down
and theme.breakpoints.between
has been adjusted based on the changes in behavior for those functions (down
is now exclusive of the specified breakpoint rather than inclusive and the end breakpoint for between
is also now exclusive, so for both of those the breakpoint specified needs to be one up from what would have been used in v4). Also, the min-width
of the media-query that is specified directly has been adjusted from 1280px
to 1200px
to match the new value of the lg
breakpoint in v5.
import React from "react";
import Button from "@material-ui/core/Button";
import { styled } from "@material-ui/core/styles";
const StyledButton = styled(Button)(({ theme }) => ({
color: "white",
[theme.breakpoints.down("sm")]: {
marginTop: theme.spacing(1),
backgroundColor: "purple"
},
[theme.breakpoints.between("sm", "lg")]: {
marginTop: theme.spacing(3),
backgroundColor: "blue"
},
"@media (min-width: 1200px)": {
marginTop: theme.spacing(5),
backgroundColor: "red"
}
}));
export default function App() {
return <StyledButton variant="contained">Hello World!</StyledButton>;
}
Documentation on changes to breakpoints from v4 to v5: https://next.material-ui.com/guides/migration-v4/#theme
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…