3

Within a create-react-app project I'm using material-ui 1.x and creating a custom theme with custom breakpoints, as such..

import {  createMuiTheme } from '@material-ui/core/styles';
let customTheme = createMuiTheme({
  breakpoints:{
    values:{
      xs: 0,
      sm: 600,
      md: 960,
      lg: 1280,
      xl: 1920
    }
  }
});
export default customTheme;

Is it possible to reference those breakpoints inside a .css file. For example, I have a layout component that uses media queries...

...
@media screen
 and (max-width: 850px) and (min-width: 640px){  /* <--- HERE   */
    .layout-content {
        grid-template-columns: 1fr 200px 200px 200px 1fr;
        grid-template-rows: 64px 
                        auto
                        1fr
                        auto;
        grid-template-areas: "h h h h h"
                             ". l m m ."
                             ". r m m ."
                             "f f f f f";
    }
}
...

Is it possible to get the values for those css media queries from the materail-ui theme object?

Tim Ellison
  • 353
  • 5
  • 10
honkskillet
  • 3,007
  • 6
  • 31
  • 47

2 Answers2

2

OK. This led to a bit of a deep dive on my part. The react material-ui (https://material-ui.com) embraces CSS-in-JS so if you are choosing to work with this framework it really makes sense to go that route, which means converting my CSS to JSS and then accessing the material-ui theme object to get the media break points. That same bit of CSS now looks like this

 [theme.breakpoints.only('sm')]:{
    layoutContent: {
      gridTemplateColumns: '1fr 200px 200px 200px 1fr',
      gridTemplateRows:`64px
                        auto
                        1fr
                        auto`,
      gridTemplateAreas: `"h h h h h"
                          ". l m m ."
                          ". r m m ."
                          "f f f f f"`,
    }
  },

Note, this is now JSON and not CSS.

honkskillet
  • 3,007
  • 6
  • 31
  • 47
1

If you're only targeting modern browsers, you may be able to use CSS custom variables. Set them in the Javascript

for (key in breakpoints.values) {
    document.body.style.setProperty(
        "--theme-breakpoint-" + key,
        breakpoint.values[key] + "px"
    );
}

and then reference them in CSS

.some-class {
    min-width: var(--theme-breakpoint-sm);
}

You can't use custom properties in media queries though, so in the particular example above you'd have to restructure your CSS. It's hard to say if that's possible without understanding the entire layout and styling.

Stephen Thomas
  • 13,843
  • 2
  • 32
  • 53