0

I'm trying to create a lightbox where the current image takes up 90% of the height of the page OR a 900px width, whichever one happens first.

Naturally, I used the code below, expecting it to fail. I was right. I tried using the aspect-ratio property (which is frowned on because of its lack of browser support), but nothing worked.

Anybody know how to achieve this?

/* Basically the lightbox container */
.modal {
  position: fixed;
  width: 100%;
  height: 100%;
}
/* Each image has the class mySlides */
.mySlides {
  max-width: 900px;
  max-height: 90%;
  margin: 15px 5%;
}

applesomthing
  • 361
  • 3
  • 19
Alexander
  • 131
  • 9
  • Does this answer your question? [How do I auto-resize an image to fit a 'div' container?](https://stackoverflow.com/questions/3029422/how-do-i-auto-resize-an-image-to-fit-a-div-container) – Peter Krebs Aug 10 '21 at 10:03
  • @PeterKrebs It would if I were willing to set fixed widths for my images. I'm trying to deal in percentages here so that each image always has a certain amount of space from the edge of the screen, not matter what device you're on. If all my images were 16/9 or something like that, my max-width:900px would work, but I have landscape AND portrait images that I'm trying to apply my code to. When I apply max-width to both a horizontal and portrait image, one or both of them will end up wrong. So I have to add in max-height to keep the portrait one from spilling offscreen, but it doesn't work. – Alexander Aug 10 '21 at 10:09
  • Not sure what wrong with just those code. It work fine in my demo [link](https://jsfiddle.net/1x9ebzhw/) – Eezo Aug 10 '21 at 10:16
  • Look into `object-fit: contain` ? – Amaury Hanser Aug 10 '21 at 10:21
  • @HenryVarro I'm really confused as to why yours works and mine doesn't. I tried adding a pixel value to the max-height of the image (max-height: 200px) just as a test, and it didn't affect the image at all. – Alexander Aug 10 '21 at 10:37
  • @AmauryHanser I just looked it up and messed around with it a bit. I think it might have worked but I'll do some more tests to confirm it. If it does, I'll post this as the answer. Thank you so much! – Alexander Aug 10 '21 at 10:38
  • Glad that you could sort it out. – Amaury Hanser Aug 10 '21 at 12:36

1 Answers1

1

Alright, a comment from Amaury Hanser got me on the right track. The solution that worked was using object-fit: contain;. This link helped me learn what that is. The property basically makes an object fit within the borders of its parent container while maintaining its aspect ratio.

This is my code now:

.modal {
  position: fixed;
  width: 100%;
  height: 100%;
}
.mySlides {
  max-width: 900px;
  max-height: 90%;
  object-fit: contain;
  margin: 15px 5%;
}
Alexander
  • 131
  • 9