防止固定定位的div在调整大小后移出屏幕
我有一个固定定位的div,里面包含一个img用来显示图片,但它显示的图片大小不一,这会让竖向图片在屏幕外出现。
如何在超出窗口边界时让它缩小尺寸(在水平方向和垂直方向都缩小,这样图片就不会被拉伸)?
以下是相关的代码片段:
HTML
<div class="showcase">
<button onclick="closeshowcase()">X</button>
<img id="showcaseimg" src="images/photography/image0.webp">
<p>this is an image</p>
</div>
CSS
.showcase{
pointer-events: none;
opacity: 0;
scale: 90%;
position: fixed;
width: 85%;
z-index: 5;
top: 50%;
left: 50%;
translate: -50% -50%;
transition: all 0.5s ease;
&.visible {
pointer-events: all;
opacity: 100;
scale: 100%;
}
}
.showcase img{
border-radius: 15px;
width: 100%;
height: 100%;
object-fit: contain;
}
解决方案
问题出在
.showcase img{
width: 100%;
height: 100%;
}
这会让图片始终填充容器,当图片过高或过宽时就会产生溢出。请使用 相对于视口的最大宽度和最大高度。
.showcase img{
border-radius: 15px;
max-width: 100%;
max-height: 80vh;
width: auto;
height: auto;
object-fit: contain;
}
此外,你还可以通过将.showcase设为一个flex容器来改进容器布局,这样无论图片大小,文本和按钮都能保持对齐
.showcase{
pointer-events: none;
opacity: 0;
scale: 90%;
position: fixed;
width: 85%;
max-height: 90vh;
display: flex;
flex-direction: column;
align-items: center;
z-index: 5;
top: 50%;
left: 50%;
translate: -50% -50%;
transition: all 0.5s ease;
}
.showcase.visible{
pointer-events: all;
opacity: 1;
scale: 1;
}
你还可以通过添加以下内容来防止横向图片过大
.showcase img{
max-width: 90vw;
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。