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

什么好主意吗?


当前回答

现在我们可以使用vw和vh单位,它们分别代表视口宽度和高度的1%。

https://css-tricks.com/fun-viewport-units/

举个例子:

img {
  max-width: 100vw;
  max-height: 100vh;
}

... 将使图像尽可能宽高,保持纵横比,但不宽或高于视口的100%。

其他回答

通过将CSS的max-width属性设置为100%,图像将填充它的父元素的宽度,但不会呈现比它的实际大小更大,从而保持分辨率。

将height属性设置为auto可以保持图像的纵横比,使用这种技术可以覆盖静态高度,并使图像能够在各个方向上按比例伸缩。

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

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

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

简单优雅的工作解决方案:

img {
  width: 600px;  /*width of parent container*/
  height: 350px; /*height of parent container*/
  object-fit: contain;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

这是一个非常直接的解决方案,我提出后,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); />

我不是想翻旧账,但是…

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

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