如何在CSS中使脱节图像的大小相同?

时间:2019-04-11 15:01:13

标签: html css html5 css3

我想做什么

like this
在同一帧中对齐各种尺寸和形状的图像。 (仅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>

1 个答案:

答案 0 :(得分:2)

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

另请参见Object-fit docs on MDN