CSS 图片缩放问题

3

我在管理面板中设置的图片大小调整时遇到了问题。

.users-list>li img {
    border-radius: 50%;
    max-width: 100%;
    height: auto;
    width: 100px;
    height: 100px;
}

当最大化时,这些图片看起来很棒:

enter image description here

。但是如果我调整浏览器大小,它们就会一起缩小:

enter image description here

。然后我尝试删除height: 100px属性,这似乎能解决问题,但其中一个图片出了问题:

enter image description here


1
使用 max-height:100px;max-width:100px; 替代 height:100px;max-width:100%; - Sebastian Brosch
宽度:100%;高度:自动; - devpro
3个回答

4
如果你不想让你的图片被拉伸,你应该锁定一个维度,同时允许另一个维度为auto。(这会保持图片的宽高比) 请看下面的例子,其中width保持不变,而height自动调整:

img {
  display: block;
}
.correct,
.incorrect {
  border: 1px solid red;
  display: inline-block;
}
.incorrect img {
  max-width: 100%;
  width: 100px;
  height: 100px;
}
.correct img {
  max-width: 100%;
  width: 200px;
  height: auto;
}
<div>This one stretches out:</div>
<div class="incorrect">
  <img src="https://via.placeholder.com/150x50" />
</div>

<div>This will preserve aspect ratio and look right:</div>
<div class="correct">
  <img src="https://via.placeholder.com/150x50" />
</div>

请看下面的示例,其中height保持不变,而width自动调整:

img {
  display: block;
}
.correct,
.incorrect {
  border: 1px solid red;
  display: inline-block;
}
.incorrect img {
  max-height: 100%;
  height: 100px;
  width: 100px;
}
.correct img {
  max-height: 100%;
  height: 200px;
  width: auto;
}
<div>This one stretches out:</div>
<div class="incorrect">
  <img src="http://placehold.it/150x50" />
</div>

<div>This will preserve aspect ratio and look right:</div>
<div class="correct">
  <img src="http://placehold.it/150x50" />
</div>


2
这非常有道理……那么我的格式就是最好的。后端需要检索相同尺寸的图像以实现我想要的功能。 - Norgul

0

你也可以在 <img> 标签中使用 height 属性。

像这样 <img src="/path/to/image" height="40">,不需要任何 CSS。


0
只需移除

标签。
height: 100px;

i.e

.users-list>li img {
    border-radius: 50%;
    max-width: 100%;
    height: auto;
    width: 100px;
}

这给了我第三张图片的结果。 - Norgul

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接