Using Material-UI breakpoints with pixel values instead of sm, md, lg, xl
I’ve got some code here
[theme.breakpoints.only('lg')]: {}
Which works and moves at the breakpoint I want. However, when I use the following
[theme.breakpoints.between('1200', '1021')]: {}
It doesn’t actually break on those points. I’m wondering how to use actual numbers in the breakpoint section in a way that mui will pick it up. I don’t want to create a new breakpoint for it.
The theme.breakpoints.between
function supports passing numbers instead of breakpoint keys. The only issue is that you are passing them in the wrong order. You need to have the lower pixel value first.
Currently your code will generate the following:
@media (min-width:1200px) and (max-width:1020.95px)
This won’t match anything because it is impossible for anything above the min-width to meet the max-width criteria.
If you swap the two parameters and do theme.breakpoints.between(1021, 1200)
, you will instead get the following (which will work much better):
@media (min-width:1021px) and (max-width:1199.95px)
It’s also worthwhile to realize that the theme.breakpoints.x
functions are just convenience methods for creating media query strings. It also works just fine in JSS styles to specify the media query directly, such as in the following example:
import React from "react"; import { makeStyles, useTheme } from "@material-ui/core/styles"; const useStyles = makeStyles({ myCustomClass: { "@media (min-width:600px) and (max-width:1199.95px)": { backgroundColor: "green" }, "@media (max-width:599.95px)": { backgroundColor: "blue" }, "@media (max-width:900px)": { color: "yellow" } } }); export default function App() { const theme = useTheme(); const classes = useStyles(); return ( <div className={classes.myCustomClass}> theme.breakpoints.between("1021", "1200"):{" "} {theme.breakpoints.between("1021", "1200")} <br /> theme.breakpoints.between("sm", "md"):{" "} {theme.breakpoints.between("sm", "md")} <br /> theme.breakpoints.only("md"): {theme.breakpoints.only("md")} </div> ); }