有没有办法让图像适合固定大小的 div 而不拉伸(stretch)它?
我的图像可以是横向或纵向以适合 250px div,问题是 ut 真的被拉伸(stretch)了。
实际图像尺寸:
当前结果:
CSS 代码:
.container {
position: relative;
width: 250px;
height: 250px;
margin-bottom: 30px;
}
.container img {
width: 100%;
height: auto;
}
HTML 代码:
<div class="row text-center text-lg-left">
<div th:each="inst, iStat : ${instances}" class="container"
th:if="${inst.fileStatus} eq ${T(br.com.macrosul.stetho.entity.FileStatus).UPLOADED}">
<a href="#" class="d-block mb-4 h-100"> <img class="img"
data-target="#showMedia" data-toggle="modal"
th:data-slide-to="${iStat.index}"
style="width: 100%; height: 100%"
th:src="@{'/instances/' + ${inst.id} + '/thumbnail' + ${folder != null ? '?folder=' + folder.id : ''}}"
alt="">
</a>
</div>
</div>
最佳答案
第一个“你的错误” - 你将 300 像素的图像放入 250 像素高度的容器中(溢出 50 像素)。设置.container
溢出到scroll
看到这个:
.container {
position: relative;
width: 250px;
height: 250px;
margin-bottom: 30px;
overflow: scroll;
}
.container img {
width: 100%;
height: auto;
}
<div class="container">
<img class="img" src="https://i.picsum.photos/id/12/200/300.jpg">
</div>
对象适合
对象拟合仅适用于 if
您调整图像或包装器的大小(并设置与此包装器相关的图像大小)。
https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
基本示例“图像调整大小”(没用):
调整图像大小object-fit cover - 400h X 800W 图像 - 将高度设置为 150hX150w - 零失真(“裁剪效果”):
<img style="width: 150px; height: 150px; object-fit: cover;" src="https://i.picsum.photos/id/10/400/800.jpg">
基本示例 2(也不是很有用)
将图像高度/宽度设置为 100%
并设置包装高度(如“窗口”)。
<div class="container" style="height: 200px;">
<img style="width: 100%; height: 100%; object-fit:cover;" class="img" src="https://i.picsum.photos/id/12/500/600.jpg">
</div>
更动态的示例:
解决这个问题的一个“著名”CSS技巧:
-
relative
wrapper (任何您想要的尺寸)&absolute
内部 100% w/h 图像 &object-fit:cover
.
使用固定大小包装
<div style="position: relative; height: 200px; width: 200px">
<img style="position: absolute; top:0; right: 0; left: 0; bottom: 0; width: 100%; height: 100%; object-fit: cover;" src="https://i.picsum.photos/id/10/400/800.jpg">
</div>
使用aspect-ratio
16:9盒子
非常非常yyyyyyyy - 有用(例如instagram网格 - 强制所有图像具有相同的宽高比)。
完整教程在这里: https://css-tricks.com/aspect-ratio-boxes/ https://css-tricks.com/aspect-ratio-boxes/
https://www.w3schools.com/howto/howto_css_aspect_ratio.asp
<h5>16:9 box</h5>
<div style="position: relative; padding-top: 56.25%;">
<img style="position: absolute; width: 100%; height: 100%; top:0; right:0; left:0; right: 0;object-fit: cover;" src="https://i.picsum.photos/id/10/700/1100.jpg">
</div>
关于html - 如何在不扭曲图像的情况下将图像放入固定大小的 div 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60938707/