gpt4 book ai didi

html - 如何仅使用 css 根据图像宽度为父级设置动态宽度

转载 作者:行者123 更新时间:2023-11-28 13:55:17 25 4
gpt4 key购买 nike

我正在使用 React 创建自己的灯箱,我想根据图像宽度在类 .lightbox-active 上设置 div 的宽度。现在,我设置了 max-width: 50%; max-height: 80% 对于父元素,例如图像只填充了父元素的 43% 我想为父元素设置 43% 的宽度。有没有办法不用js计算宽度就可以实现?

<div className="lightbox-active">
<img onLoad={() => isFinished()} src={fakeImages[openedImage - 1].url} alt="" />
</div>

我的图像有属性 object-fit: contain 并且我需要它来以原始比例显示图像,没有这个图像填充 50% 宽度作为它的父但溢出高度。

工作示例:

https://codepen.io/freestyle09/pen/rNNdNNg

边框绿色应该像图片一样大小

* {
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>

最佳答案

我有一个解决方案,可以使用 position: absolute 来实现。它可以随心所欲地为您工作。

您必须修改 .lightbox-active.lightbox-active img 的 css 才能使用绝对定位。

* {
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 {
max-width: 50%;
max-height: 80%;
border: 1px solid red;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}

.lightbox-active img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
border: 2px solid green;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
<div class="lightbox">
<div class="lightbox-active">
<img src='https://picsum.photos/1503/1500' alt="" />
</div>
</div>

关于html - 如何仅使用 css 根据图像宽度为父级设置动态宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58710087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com