Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Device width and height in material-ui

I am trying to add the specific width and height of (Iphone 7 Plus) only. For the project I am using withStyles.

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

I tried using:

"@media (width: 414px) and (height: 628px)": {}

I tried "@media (device-width: 414px) and (device-height: 628px)": {} Tried both examples and is not working. Does someone have any ideas how to do it? Thank you

like image 549
Mihail Avatar asked Apr 22 '26 18:04

Mihail


2 Answers

There is nothing wrong in your media query, but you haven't provided the full code, so I'm suspecting that either you are writing the media query in the wrong place or might have misused the withStyles().

So right now I'm working on a project which uses Material UI.

I tried adding media query specified by you in my styles for the <Toolbar> which resides inside the <AppBar> component. By default the toolbar is using the dark blue accent as a background color (set inside the global theme).

The media query will override the background color with #000 when it has screen width: 414px and height: 628px.

Here's the working code for you, created using a template from MUI docs and added media query in the styles:

https://codesandbox.io/s/jolly-elgamal-83von?file=/src/App.js&resolutionWidth=414&resolutionHeight=628

Try adjusting the screen size in the output window, you'll see media query affecting the styles.

Explanation:

Make sure you are following these two things:

  • I am using makeStyles() hook, whereas you are using withStyles(), doesn't have any difference between these two. But make sure that if you have function component then you should use makeStyles() and useStyles() hook calls to apply styles, Or else if you are using class component then you can go with withStyles() way.
  • Also, make sure that you are not using the media-queries like we do it in the CSS. You need to use it inside the class, here my class is toolbar which is key inside the styles. Used as a className={styles.toolbar} for the <Toolbar> component.

Here's my code:

function Navbar() {
  const useStyles = makeStyles(() => ({
    toolbar: {
      '@media (width: 414px) and (height: 628px)': {
        background: '#000',
      },
    },
  }));

  const styles = useStyles();

  return (
    <AppBar position="static">
      <Toolbar className={styles.toolbar}>
      </Toolbar>
    </AppBar>
  );
}

enter image description here

like image 190
Prathamesh Koshti Avatar answered Apr 25 '26 09:04

Prathamesh Koshti


Try using "vh" and "vw" and ur unit of size instead of "px",

vh means veiwport height,

vw means veiwport width.

7vh means 7% of the veiwport


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!