Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material UI dialog, fit image inside dialog's height

I have a Material UI dialog that will display a bunch of images, the images have landscapes or portraits aspect ratio. And they might have different resolutions as well. I want to find an elegant solution to maintain the dialog's height 80% of the screen.

But fit the whole image inside the dialog, without needing to scroll, here's a SandboxExample.

Or find the snippet bellow:

<div>
  <Button variant="outlined" color="primary" onClick={handleClickOpen}>
    Open dialog
  </Button>
  <Dialog
    open={open}
    onClose={handleClose}
    hasCloseButton
    style={{ maxWidth: "100%", maxHeight: "100%" }}
  >
    <img
      style={{ maxWidth: "100%", height: 'auto' }}
      src="https://images.unsplash.com/photo-1565992441121-4367c2967103"
      alt="image"
    />
  </Dialog>
</div>
like image 753
Valerxx22 Avatar asked Oct 21 '25 00:10

Valerxx22


2 Answers

to achieve that you may use viewheight unit (vh). Combine maxHeight(based on vh) along maxWidth: 100%. Dialog uses 32px as margin, hence you could use maxHeight: "calc(100vh - 64px)" or you can use a custom vh like maxHeight: "80vh"

   <img
      style={{ maxWidth: "100%", maxHeight: "calc(100vh - 64px)" }}
      src="https://images.unsplash.com/photo-1565992441121-4367c2967103"
      alt="image"
    />
like image 117
buzatto Avatar answered Oct 22 '25 19:10

buzatto


Can't you set the image height to 100% the element that contains it?

On your sandbox I did this: style={{ width: 'auto', height: '100%' }} and it seemed to work.

Here is the complete code:

<div>
  <Button variant="outlined" color="primary" onClick={handleClickOpen}>
    Open dialog
  </Button>
  <Dialog
    open={open}
    onClose={handleClose}
    hasCloseButton
    style={{ maxWidth: "100%", maxHeight: "100%" }}
  >
    <img
      style={{ width: 'auto', height: '100%' }}
      src="https://images.unsplash.com/photo-1565992441121-4367c2967103"
      alt="image"
    />
  </Dialog>
</div>
like image 40
Felipe Avatar answered Oct 22 '25 20:10

Felipe



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!