Wanna see something cool? Check out Angular Spotify 🎧

Align React Material UI Dialog to the top instead of center

As you work with Material Dialog, you should know that its default position is always to the center of the page. But more often, we want to make the dialog stick to the top instead.

1. For scroll='paper'

By default, the dialog alignment styles were inside the .MuiDialog-scrollPaper class with display: flex. So to easily change the position to the top, we only need to adjust align-items to flex-start and voila, the dialog now is displaying on the top as we expected.

Align React Material UI Dialog to the top instead of center

2. For scroll='body'

.MuiDialog-paperScrollBody class with display: inline-block define the dialog position center. We need to adjust the vertical-align to top to make the dialog stay at the top.

Align React Material UI Dialog to the top instead of center

Source code

Don’t use position: absolute or fixed because it will mess up the scroll behavior of the dialog

To always make the Material Dialog stay at the top of the page, you need to customize both class scrollPaper and paperScrollBody, as I mentioned above. The code will look like

const useStyles = makeStyles({
  topScrollPaper: {
    alignItems: 'flex-start',
  },
  topPaperScrollBody: {
    verticalAlign: 'top',
  },
})

function SimpleDialog(props: SimpleDialogProps) {
  const classes = useStyles()
  return (
    <Dialog
      onClose={handleClose}
      aria-labelledby="simple-dialog-title"
      open={open}
      scroll="paper"
      classes={{
        scrollPaper: classes.topScrollPaper,
        paperScrollBody: classes.topPaperScrollBody,
      }}
    ></Dialog>
  )
}

Demo

View on codesanbox

Published 10 Jul 2021

Read more

 — TypeScript - Property 'onerror' does not exist on type 'EventTarget'
 — TypeScript data structure: Stack
 — TypeScript data structure: Queue
 — TypeScript data structure: Singly linked list
 — Difference between: function Person(){}, var person = Person(), and var person = new Person()?