图像方面填充模式:CSS

问题描述 投票:0回答:1

我是iOS开发人员。我们在imageview上有方面填充属性。此属性允许图像填充目标视口或容器,但保持纵横比。

现在以某种方式填充作品,这是我用纯css无法实现的。我要写下面的代码。并且解释我的需求很难用英语来表达它,所以请尽量忍受它并且有耐心。所以这里是:

Aspect Fill:仅填充所需的比例因子。例如:如果图像大于视口大小,则图像将缩小以保持纵横比,直到它变得小于视口,否则它将是“适合”效果。它必须填充视口。超出视口范围的额外部分将被剪掉。

如果图像小于视口,则图像将按比例放大,保持纵横比,直到它只填充视口。超出视口范围的额外部分将被剪掉。

填充比例因子很重要。我希望我解释了我的需要。在尝试在网上学习以实现我想出下面的代码。这段代码没有填写我想要的方式。它保持纵横比,但填充100%缩放或缩放。

.page-container, .page {
  width: 320px;
  height: 480px;
}

.page {                     
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.page-image {
  flex-shrink: 0;
  min-width: 100%;
  min-height: 100%;
}
<div class="page-container">
  <div class="page">
     <img class="page-image" src="https://images.unsplash.com/photo-1495974887311-a817001ebd74" alt="">
  </div>
</div>

您可以在unsplash链接中查看原始图像。你可以测试较小的图像:https://upload.wikimedia.org/wikipedia/commons/5/50/Salta-VallesCalchaquies-P3140151.JPG

这个模式可以在纯css中实现吗?或者我是否需要javascript来根据我的要求操作方面填充视口的每个图像的新大小?

html css
1个回答
0
投票

您可以在图像类中使用object-fit: cover;

您还需要将widthheight添加到图像中。 (注意:它在Internet Explorer上不起作用,但您可以添加polyfill like this!以使其在那里工作)。

以下是基于您的代码的示例:

.page-container, .page {
  width: 320px;
  height: 480px;
}

.page {                     
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.page-image {
  flex-shrink: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div class="page-container">
  <div class="page">
     <img class="page-image" src="https://images.unsplash.com/photo-1495974887311-a817001ebd74" alt="">
  </div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.