I'm currently working on developing my own lightbox using React, and I am looking to adjust the width of a div with the class .lightbox-active
based on the width of the image it contains. Right now, I have set the parent element to have a max-width: 50%; max-height: 80%
, but I want the parent div's width to match the percentage that the image is occupying within the parent element. Is there a way to achieve this without having to calculate the width in JavaScript?
<div className="lightbox-active">
<img onLoad={() => isFinished()} src={fakeImages[openedImage - 1].url} alt="" />
</div>
The image has the property object-fit: contain
which is essential for displaying the image in its original proportions. Without this property, the image fills 50% of the width as its parent but overflows in height.
Here is a link to a working example:
https://codepen.io/freestyle09/pen/rNNdNNg
The green border should match the size of the image:
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
.lightbox {
position: fixed;
top: 0;
left: 0;
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,.3);
}
.lightbox-active {
display: flex;
justify-content: center;
max-width: 50%;
max-height: 80%;
border: 1px solid red;
}
.lightbox-active img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
border: 2px solid green;
}
<div class="lightbox">
<div class="lightbox-active">
<img src='https://picsum.photos/1503/1500' alt="" />
</div>
</div>