CSS:图像溢出

新手上路,请多包涵

我正在尝试使图像适合黑色边框 div,无论它们是否旋转。我尝试过溢出:隐藏,最大高度:100% 和对象拟合:包含但仍然图像溢出。与变换。我不知道下一步该尝试什么。需要帮忙

<div style="border: 1px solid">
  <img img-fix-orientation="model.post.image" ng-src="{{model.post.image ? model.post.image : model.post.sub_category.name == 'Service' ? 'images/service.png' : 'images/thing.png'}}" style="max-width:100%;" alt="post image" />
</div>

检查元素样式和图像

原文由 MTA 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 975
2 个回答

请注意, object-fit 缺乏良好的浏览器支持,并且有一些选项可以克服,尽管在这里我想展示 contain 如何适用于和不带 transform .

To show an image in an img element uncut, you use the object-fit: contain , set width and /or height to 100% 它将使垂直和水平图像都适合而不会溢出。

 .wrapper {
  display: inline-block;
  height: 150px;
  width: 250px;
  padding: 5px;
  margin: 5px;
  background: lightgray;
}

.wrapper img {
  height: 100%;
  width: 100%;
  object-fit: contain;
}
 <div class="wrapper">
  <img src="http://placehold.it/150x300/f00"/>
</div>

<div class="wrapper">
  <img src="http://placehold.it/300x150/00f"/>
</div>

现在,当您应用 transform: rotate(90deg) 它只是在 视觉上 这样做,所以从文档流的角度来看,它仍然像上面的示例一样调整大小/定位。

这意味着 wrapperimg 都没有意识到任何变化,因此当水平旋转 wrapper img 到垂直时会溢出 ---

为了能够旋转这样的 img 并使其垂直适合, transform 需要事先知道 wrapper 的纵横比,以便能够补偿溢出,在这个示例中它是已知的 (150px / 250px = 0.6),因此通过将 scale 添加到转换中,我们可以避免溢出。

 .wrapper {
  display: inline-block;
  height: 150px;
  width: 250px;
  padding: 5px;
  margin: 5px;
  background: lightgray;
}

.wrapper img {
  height: 100%;
  width: 100%;
  object-fit: contain;
  transform: rotate(90deg) scale(0.6);
}
 <div class="wrapper">
  <img src="http://placehold.it/300x150/00f"/>
</div>

对于垂直 img 在垂直 wrapper 需要应用相同的修复。

原文由 Asons 发布,翻译遵循 CC BY-SA 3.0 许可协议

有几种方法可以使这项工作。您可以指定包含元素的高度,同时将 overflow-y 属性设置为 hidden 。 (必须设置一个高度……没有设置一个,浏览器怎么知道什么是溢出?)

 .container {
  border: 1px solid black;
  height: 100px;
  overflow-y: hidden;
}

.img {}
 <div class="container">
  <img src="http://via.placeholder.com/150x150"/>
</div>

<p>Image element is 150px tall, but the containing element is only 100px tall</p>

您还可以将 img 设置为背景图像,然后使用 background-size: contain 属性。 这将保留图像的原始大小

 .container-sm {
  background: url('https://i.stack.imgur.com/pHXH4.png') center center no-repeat;
  background-size: contain;
  border: 1px solid black;
  height: 50px;
}

.container-lg {
  background: url('https://i.stack.imgur.com/pHXH4.png') center center no-repeat;
  background-size: contain;
  border: 1px solid black;
  height: 200px;
}
 <div class="container-lg"></div>
<br/>
<div class="container-sm"></div>

<p>Image is fully contained in div, regardless of image or div size.</p>

希望这可以帮助!

原文由 Rich 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏