目前,使用STYLE,我可以使用width: 100%和auto on height(反之亦然),但我仍然不能将图像约束到特定的位置,要么太宽,要么太高,分别。

什么好主意吗?


当前回答

我将此用于高度和宽度固定的矩形容器,但图像大小不同。

img {
  max-width: 95%;
  max-height: 15em;
  width: auto !important;
}

其他回答

我将此用于高度和宽度固定的矩形容器,但图像大小不同。

img {
  max-width: 95%;
  max-height: 15em;
  width: auto !important;
}

也有同样的问题。对我来说,问题是高度属性也已经在其他地方定义,像这样固定它:

.img{
    max-width: 100%;
    max-height: 100%;
    height: inherit !important;
}

我不是想翻旧账,但是…

#container img {
      max-width:100%;
      height:auto !important;
}

即使这是不合适的,因为你使用!重要的覆盖高度,如果你使用CMS,如WordPress,为你设置高度和宽度,这工作得很好。

最好在应该尊重纵横比的尺寸上使用auto。如果你没有将另一个属性设置为auto,现在大多数浏览器会假设你想要尊重纵横比例,但不是所有的浏览器都这样(例如,windows phone 8上的IE10就不这样)。

width: 100%;
height: auto;

简单的解决方案:

min-height: 100%;
min-width: 100%;
width: auto;
height: auto;
margin: 0;
padding: 0;

顺便说一下,如果你想把它放在父div容器的居中,你可以添加这些css属性:

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

它应该真的像预期的那样工作:)