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

什么好主意吗?


当前回答

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

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

其他回答

我不是想翻旧账,但是…

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

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

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

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

其中一个答案包括background-size: contains css语句,我很喜欢这个语句,因为它直接说明了你想做什么,浏览器就会完成它。

不幸的是,迟早你会需要应用一个阴影,不幸的是,它不会很好地与背景图像解决方案。

假设你有一个响应性很强的容器,但是它对最小和最大宽度和高度有很好的定义。

.photo {
  max-width: 150px;
  min-width: 75px;
  max-height: 150px;
  min-height: 75px;
}

容器有一个img,它必须知道容器高度的像素,以避免得到一个非常高的图像,溢出或裁剪。

img还应该定义一个max-width为100%,首先是为了允许更小的宽度被渲染,其次是基于百分比的,这使得它成为参数。

.photo > img {
  max-width: 100%;
  max-height: 150px;
  -webkit-box-shadow: 0 0 13px 3px rgba(0,0,0,1);
  -moz-box-shadow:    0 0 13px 3px rgba(0,0,0,1);
  box-shadow:         0 0 13px 3px rgba(0,0,0,1);
}

注意,它有一个漂亮的阴影;)

享受一个活生生的例子在这小提琴:http://jsfiddle.net/pligor/gx8qthqL/2/

这是一个非常直接的解决方案,我提出后,conca的链接,并查看背景大小。它将图像放大,然后将其置于外部容器中,不缩放。

<style>
#cropcontainer
{
  width:  100%; 
  height: 100%; 
  background-size: 140%;
  background-position: center;
  background-repeat: no-repeat;
}
</style>

<div id="cropcontainer" style="background-image: url(yoururl); />

几年后,在寻找同样的需求时,我发现了一个使用background-size的CSS选项。

它应该可以在现代浏览器(IE9+)中运行。

<div id="container" style="background-image:url(myimage.png)">
</div>

以及风格:

#container
{
  width:  100px; /*or 70%, or what you want*/
  height: 200px; /*or 70%, or what you want*/
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

参考资料:http://www.w3schools.com/cssref/css3_pr_background-size.asp

demo: http://www.w3schools.com/cssref/playit.asp?filename=playcss_background-size