0

我试图弄清楚如何object-fit正确缩放 16:9 垂直图像。

我几乎没有运气尝试过任何事情!

https://jsfiddle.net/pdocys3j/

.container {
  width: 300px; /*any size*/
  height: 200px; /*any size*/
}

.object-fit-cover {
  width: 100%;
  height: 100%;
  object-fit: cover; /*magic*/
}
<div class="container">
  <img class="object-fit-cover" src="https://jardim-plant-images-development.s3.amazonaws.com/hfj1h9jq2q8o8tyv1r6dxhi4zrmn">
</div>

预期结果(不使用object-fit

.container {
  width: 300px; /*any size*/
  height: 200px; /*any size*/
  overflow: hidden;
}

.object-fit-cover {
  width: 100%;
  margin-top: -50%;
}
<div class="container">
  <img class="object-fit-cover" src="https://jardim-plant-images-development.s3.amazonaws.com/hfj1h9jq2q8o8tyv1r6dxhi4zrmn">
</div>

我希望我可以object-fit改用。对这种方法的想法?

4

2 回答 2

-1

只需添加position: relative到容器中。这会指示其子项的宽度和高度与此容器的宽度和高度相关(在本例中为 200 x 200 像素)。

.container {
  width: 200px; /*any size*/
  height: 200px; /*any size*/
  position: relative;
}

.object-fit-cover {
  width: 100%;
  height: 100%;
  object-fit: cover; /*magic*/
}
<div class="container">
  <img 
    class="object-fit-cover" 
    src="https://jardim-plant-images-development.s3.amazonaws.com/hfj1h9jq2q8o8tyv1r6dxhi4zrmn">
</div>

如果你想让它响应,你应该添加一个额外的容器:

.container {
  width: 100%;
  max-width: 300px; /*any size*/
}

.innercontainer {
  padding-bottom: 100%; /* 1:1 ratio */
  position: relative;
}

.object-fit-cover {
  position: absolute;
  width: 100%;
  height: 100%;
  object-fit: cover; /*magic*/
}
<div class="container">
 <div class="innercontainer">
  <img 
    class="object-fit-cover" 
    src="https://jardim-plant-images-development.s3.amazonaws.com/hfj1h9jq2q8o8tyv1r6dxhi4zrmn">
 </div>
</div>

于 2020-05-02T20:58:24.020 回答
-1

你可以写:

.container {
  max-width: 300px;
}

.object-fit-cover {
  object-fit: cover;
  width: 100%;
  height: 100%;
}
<div class="container">
  <img class="object-fit-cover" src="https://jardim-plant-images-development.s3.amazonaws.com/hfj1h9jq2q8o8tyv1r6dxhi4zrmn">
</div>

于 2020-05-02T20:52:53.270 回答