强制图像在宽度变化时保持原生高度

时间:2016-01-21 18:32:52

标签: html css image

https://jsfiddle.net/q97jn9jp/

我有一些图片,但我不知道它是widthheight。我希望它是100%宽,但我希望它的高度保持自然(如果图像高度为100px我希望它始终保持100px)。

这可能吗?

我不想使用javascript。

img {
  width: 100%;
  //height: ???;
}
<img src="https://placehold.it/100x100" alt="">

6 个答案:

答案 0 :(得分:5)

我意识到这里的目标是不必使用特定于图像的样式。但是,如果此限制仅适用于维度,则可能有效:

&#13;
&#13;
.stretchy {
  background-image: url(https://placehold.it/100x100);
  background-size: 100% 100%;
}
.stretchy img {
  display: block; /* eliminates descender space inherent with inline elements */
  visibility: hidden;
}
&#13;
<div class="stretchy">
  <img src="https://placehold.it/100x100" alt="">
</div>
&#13;
&#13;
&#13;

Fiddle

答案 1 :(得分:1)

没有办法保持它的高度,没有javascript就将宽度设置为100%。

答案 2 :(得分:0)

修改

纯CSS和传统图像不可能

CSS没有提供任何机制来将图像的自然高度或宽度声明为值。

如果不使用JavaScript或changing your markup and using background-image as suggested by @isherwood,则无法执行您的要求。

你能得到的最接近的是提前知道图像高度。

&#13;
&#13;
img {
  width: 100%;
  height: 100px;
}
&#13;
<img src="https://placehold.it/900x100" /><br />
<img src="https://placehold.it/450x100" /><br />
<img src="https://placehold.it/100x100" />
&#13;
&#13;
&#13;

但您可以使用JavaScript (即使您不想)在页面加载时动态设置高度。 jQuery示例:

&#13;
&#13;
$(function () {
  $('img').each(function () {
    var $this  = $(this),
        height = $this.height();
    $this.css({
        width : "100%",
        height: height
    });
  });
});
&#13;
/* Ensure images load in natural sizes initially */
img {
  width: auto;
  height: auto;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://placehold.it/900x100" /><br />
<img src="https://placehold.it/450x100" /><br />
<img src="https://placehold.it/100x100" />
&#13;
&#13;
&#13;

答案 3 :(得分:-1)

如果你想保持图片的比例,你必须使用:

&#13;
&#13;
height: auto;
&#13;
&#13;
&#13;

答案 4 :(得分:-2)

您需要一个自适应图像类,它会自动将图像调整为视口宽度并动态更改其高度。

.image-responsive {
    display: block;
    height: auto;
    max-width: 100%;
}

关键是使图像成为具有自动确定高度的块级元素,同时将宽度限制为可用列的100%。

答案 5 :(得分:-2)

编辑:对不起,我误读了你开始看小提琴时你不知道高度。我基于那张图片。

首先,让我们解释一下%的工作原理。

当按百分比调整大小时,它基本上会“填充”它的容器。通过将中间分隔线拖动到不同的大小,您可以看到它在您提供的小提琴中是如何工作的。

在这个小提琴中:https://jsfiddle.net/q97jn9jp/3/

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

您可以看到图像高度保持100px,或者它是您解释的自然高度。宽度延伸以填充容器宽度。

同样地,如果你不包括高度,它将随着宽度而缩放,这正是你在小提琴中所经历的。

希望这会有所帮助。