html - 以已知大小在 div 中居中图像。使用所有高度或所有宽度。保持正确的比例。没有裁剪

标签 html image css

我有一个已知大小的方形 div。

我想显示一张大小未知的图片。

我要:

.在保持图片大小比例的情况下,利用div中的最大空间展示图片。

.要居中的图像,如果图像高大于宽则水平居中,或者如果图像宽大于高则垂直居中。

.我不希望图像被裁剪

.我不希望图像被拉伸(stretch)并使用整个 div

.图像应保持其比例

我可以使用 html img 标签或 CSS 背景图片属性

最佳答案

感谢@CBroe 和他使用背景大小的建议,我找到了解决方案

.container {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  background-repeat: no-repeat;
  background-position: center; 
  background-size: contain;
}

.container1 {
  background-image: url('http://placehold.it/30x50');
}
.container2 {
  background-image: url('http://placehold.it/50x30');
}
.container3 {
  background-image: url('http://placehold.it/500x300');
}
.container4 {
  background-image: url('http://placehold.it/300x500');
}
<div class="container container1">
</div>
<div class="container container2">
</div>
<div class="container container3">
</div>
<div class="container container4">
</div>

关于html - 以已知大小在 div 中居中图像。使用所有高度或所有宽度。保持正确的比例。没有裁剪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40847278/

相关文章:

html - 如何在不使用图像且不添加任何标记的情况下在 css 中将边框作为背景?

android - 在 Android 上 react Native Circle Image

html - Ionic Angular ion-img 和后备图像问题

html - 内容 block 变得可链接,无需任何命令

html - 如何在纯CSS中创建颜色自定义滚动条?

java - 无法将空值分配给原始类型错误(Spring/Hibernate)

html - CSS 中左浮动 div 的负右边距有什么用?

javascript - 在 Angular 8 中加载页面时,CSS 会分散

html - img 标签不适用于 src 中的相对路径

css - WordPress 短代码无法正常工作