我在可调整大小的div中有一个图像,如下所示:

jsfiddle

#img_wrapper{
  resize: both;
  overflow: hidden;
  background-color:gray;
  height:15rem;
  width:15rem;
  
  min-height:15rem;
  min-width:15rem;
  user-select:none;
  
}

#img_testing{
    display:block;
    
    position:relative;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
    
    width:70%;

}
<div id="img_wrapper">
  <img src="https://i.ibb.co/zJvjmKs/icon.png" id="img_testing">
</div>

我试图将图像的纵横比保持在div调整后的大小上

例如:

This is correct
enter image description here

This is incorrect
enter image description here

Whereas it should look like this:
enter image description here

推荐答案

可以使用"最大高度"(max height)和"宽度"(width)值,然后使用"对象拟合"(object fit)属性强制调整图像的比例

#img_wrapper {
  resize: both;
  overflow: hidden;
  background-color: gray;
  height: 15rem;
  width: 15rem;
  min-height: 15rem;
  min-width: 15rem;
  user-select: none;
}

#img_testing {
  display: block;
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  height: auto;
  width: 70%;
  max-width: 70%;
  max-height: 70%;
  object-fit: contain;
}
<div id="img_wrapper">
  <img src="https://i.ibb.co/zJvjmKs/icon.png" id="img_testing">
</div>

Html相关问答推荐

在CSS中不保持圆形图像形状的边框半径属性

CSS:显示块,第一个项目没有正确对齐

将输入字段下方的两个按钮设置为两侧对齐

react :事件和转发器在特定代码段中不起作用

在一行中对齐文本和图标

Chatbox底部显示新消息,并向上推送旧消息

如何制作带有粘性头和脚的可滚动车身

30000ms后超时重试:期望找到元素:someElement,但从未找到它

在屏幕上每行 css 中的特定列居中

如何修剪 flex: 1 内的垂直文本?

复制两个

会产生一个空行;复制

元素不会

动态计算高度时 Div 不保持 1/1 纵横比

在 CSS 中的 div 中获取文本以环绕其他文本?

使用 R markdown 在 html 中包含图像

pull-right 不适用于 bootstrap alert 内的按钮

如何使用动画拆分和对齐文本块

重点/主动输入的概述问题

将 HTML 元素粘贴到容器底部,而不剪裁其顶部

在随机图像下对齐文本

如何在 Revel 模板中更改动态变量