使用 CSS 缩放图像但限制为原始大小

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

为了响应式设计,我想缩小一些图片:

img {
    width:100%;
    height:auto;
}

这按预期工作,但如果屏幕宽度超过图像的原始尺寸,它会炸毁图像。

有没有办法将这种缩放限制为其原始大小?这样它只会在必要时变小?

提前感谢您的回答。

威廉

css fluid-layout
4个回答
13
投票

您可以使用

max-width
来防止图像宽度变得大于原始尺寸。

img {
    width: auto;
    max-width: 100%;
    height: auto;
}

4
投票

不回答图像大小限制的比例错误这可能有效:

img {
  max-height: max-content;
}

0
投票

将图像放在

<div>
中并给
<div>
一个最大宽度。

CSS

#test {
    max-width: 400px;
}
img {
    width:100%;
    height:auto;
}

HTML

<div id="test">
    <img src="http://a.dilcdn.com/bl/wp-content/uploads/sites/8/2012/09/02-11.jpg" />
</div>

JSfiddle


0
投票

这对我有用。

CSS:

.captioned-image{
    margin: auto;
    text-align: center;
}

.captioned-image img{
    width: 100%; 
}

HTML

<div class="captioned-image">
    <img src="/img/my_image.jpg" style="width:max-content; max-width:max-content;">
</div>

您不需要像我在这里所做的那样覆盖 html 中的“宽度”属性——我在自己的项目中就是这样做的。我确定像下面这样的 css 类可以工作,但我想粘贴我的确切代码。

.img{
    max-width: max-content;
    width: max-content;
}
© www.soinside.com 2019 - 2024. All rights reserved.