html - 如何在 CSS 中使脱节图像的大小相同?
问题描述
我想做的事
在同一帧中对齐各种尺寸和形状的图像。(仅限 CSS)
随着浏览器大小的变化,图像大小也会按比例变化。
当前状态
JSFiddle
目前,只有水平图像效果很好。
较小的图像变大,较大的图像变小并适合框架内。
正如您在 Fiddle 演示中看到的那样,方形和垂直效果不好。
我怎样才能为所有形状做到这一点?
代码
它与 JSFiddle 完全相同。
建议你看 JSFiddle,因为显示可能有点奇怪。
/* swiper (doesn't matter) */
var swiperCnt = new Swiper('.swiperCnt', {
direction: 'vertical',
autoHeight: true,
pagination: {
el: '.swiper-pagination',
type: 'bullets',
clickable: 'true',
},
keyboard: {
enabled: true,
},
mousewheel: {
forceToAxis: true,
invert: true,
},
});
/* The orange "big square" is crushed by the "small vertical" below and is less visible. */
.swiper-slide {
display: flex;
align-items: center;
padding: 1%;
}
.swiper-slide img {
width: 100%;
}
.swiper-container {
displey: flex;
width: 400px;
height: 300px;
}
p {
white-space: pre-wrap;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.5.0/css/swiper.min.css" rel="stylesheet"/>
<div class="swiper-pagination"></div>
<div class="swiper-container swiperCnt max">
<div class="swiper-wrapper imgs max-inner">
<div class="swiper-slide"><img class="work" src="https://placehold.jp/ed3232/ffffff/200x100.png?text=small%20horizontal" alt="smallHorizontal" /></div>
<div class="swiper-slide"><img class="work" src="https://placehold.jp/392fed/ffffff/500x350.png?text=big%20horizontal" alt="bigHorizontal" /></div>
<div class="swiper-slide"><img class="work" src="https://placehold.jp/beed2f/424242/100x100.png?text=small%20square" alt="smallSquare" /></div>
<div class="swiper-slide"><img class="work" src="https://placehold.jp/edab2f/ffffff/800x800.png?text=big%20square" alt="bigSquare" /></div>
<div class="swiper-slide"><img class="work" src="https://placehold.jp/ed3232/ffffff/100x250.png?text=small%20vertical" alt="smallVertical" /></div>
<div class="swiper-slide"><img class="work" src="https://placehold.jp/392fed/ffffff/500x600.png?text=big%20vertical" alt="bigVertical" /></div>
</div>
</div>
<p>
1) small horizontal 2) big horizontal 3) small square 4) big square 5) small vertical 6) big vertical
</p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.5.0/js/swiper.min.js"></script>
解决方案
设置图片的图片宽度和高度并使用object-fit: contain;
.swiper-slide {
box-sizing: border-box; // <-- needed to compensate for padding
display: flex;
align-items: center;
padding: 1%;
img {
width: 100%; // <-- set width
height: 100%; // <-- set height
object-fit: contain; // <-- makes sure image fits 100% x 100%x
}
}
推荐阅读
- templates - 从 YAML 管道到模板文件的 Azure 管道动态参数
- react-native - 如何设置单页的跳转方式2
- angular - Angular - 使用 ngif 为同一列准备多个条件
- python - 努力验证(存在,然后是数字,然后是范围)。我想我需要使用 try 和 if 语句
- python-3.x - 如果其中一个列值与另一个数组匹配,则返回具有唯一 ID 的数据帧及其所有行
- python - 如何找到具有相同 xpath 的 2 个文本?
- sendbird - SendBird 有什么好的示例/示例/演示应用程序吗?
- php - 如何根据当前日期生成一年期?
- java - Java,存储方法引用供以后执行
- docker - 组中每个主机的 Ansible docker-compose