首页 > 解决方案 > 如何在 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>

标签: htmlcss

解决方案


设置图片的图片宽度和高度并使用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
  }
}

JSfiddle

另请参阅MDN 上的 Object-fit 文档


推荐阅读