Search code examples
reactjsmaterial-uimodern-ui

z-index not working with material ui reactjs | how can I show an element top?


I want to show another Box component above Modal component. Both are material ui component.

There is Parent Box component and there is another Box component inside Parent Box component.

Thing I want to do is show the second/child Box component on the top.

Right now it seems like the second/child Box component is under the image.

You can click a open modal button and inspect modal. You will see there will be <img />, <div></div> and <svg />

<div></div> should be Box component but I can't see it over the top.

  return (
    <div>
      <Button onClick={handleOpen}>Open modal</Button>
      <Modal
        open={open}
        onClose={handleClose}
        aria-labelledby="modal-modal-title"
        aria-describedby="modal-modal-description"
      >
        <Box  // parent Box component
          sx={{
            ...style,
            width: width,
            height: height
          }}
          className={classes.imageExpand}
        >
          <img
            src="https://cdn.pixabay.com/photo/2022/06/13/15/36/grain-7260250__340.jpg"
            alt="sample"
            className={classes.imageExpand}
          />
          <Box className={classes.conainer} />  // child Box component
          <CloseIcon className={classes.closeIcon} />
        </Box>
      </Modal>
    </div>
  );

Attempts

1, set z-index:1000 and position:'relative'

2, set lower z-index to the parent component

3, z-index:'1000 !important'

4, set transform and opacity

None of them worked. Is there any other way to show <Box /> top?

I even tried to switch Box component to regular div tag and this also doesn't work.


Solution

  • Several MUI components utilize z-index, employing a default z-index scale in MUI that has been designed to properly layer drawers, modals, snackbars, tooltips, and more.
    The z-index values start at an arbitrary number, high and specific enough to ideally avoid conflicts:

    mobile stepper: 1000
    fab: 1050
    speed dial: 1050
    app bar: 1100
    drawer: 1200
    modal: 1300
    snackbar: 1400
    tooltip: 1500
    

    so you should use a z-index greater than 1300.

    you can get more info at https://mui.com/material-ui/customization/z-index/