CSS图像大小适合嵌套div

时间:2017-01-03 21:30:58

标签: html css image

我正在尝试将超大尺寸的图像缩放到嵌套div的大小。我已经看过几乎所有建议设置max-width或max-height的Stack问题,但这对我的情况不起作用。请看我的代码:



#parent2 {
  height: 100%;
  width: 100%;
}
#parent {
  height: 25%;
  width: 50%;
}
#parent img {
  max-height: 100%;
}

<div id="parent2">
  <div id="parent">
    <img src="http://lorempixel.com/1000/1000">
  </div>
</div>
&#13;
&#13;
&#13;

6 个答案:

答案 0 :(得分:1)

您应该使用max-width而不是max-height

这是一个有效的例子:

&#13;
&#13;
#parent2 {
    height: 100%;
    width: 100%;
}
#parent {
    height: 25%;
    width: 50%;
}
#parent img {
    max-width: 100%;
}
&#13;
<div id="parent2">
  <div id="parent">
      <img src="http://lorempixel.com/1000/1000">
  </div>
</div>
&#13;
&#13;
&#13;

这是你的jsfiddle的一个分支:
https://jsfiddle.net/358vt90e/

答案 1 :(得分:0)

尝试KeyInfo而不是background-size: cover;

https://jsfiddle.net/pq17nzfh/1/

答案 2 :(得分:0)

您也可以使用:

#parent img {
    width: inherit;
}

答案 3 :(得分:0)

我为你添加了一堆不同的案例。请记住,object-fit的浏览器支持非常糟糕。如果你想使用它,你需要填充。

#parent2 {
  height: 100vh;
  width: 100%;
}
#parent {
  height: 25%;
  width: 50%;
}
#parent img {
  /* uncomment code below if you want image to respond to parent height */
  /*
  width: auto;
  height: 100%;
  */
  
  /* uncomment code below if you want image to respond to parent width */
  /*
  width: 100%;
  height: auto;
  */
  
  /* uncomment code below if you want image to respond to parent height and width */
  width: 100%;
  height: 100%;
  object-fit: cover;
  object-position: center;
}
<div id="parent2">
  <div id="parent">
      <img src="http://lorempixel.com/1000/1000">
  </div>
</div>

答案 4 :(得分:0)

使用

  

最大宽度:100%;

#parent2 {
    height: 100%;
    width: 100%;
}

#parent img {
   max-width:100%;
}
<div id="parent2">
  <div id="parent">
      <img src="http://lorempixel.com/1000/1000">
  </div>
</div>

答案 5 :(得分:0)

使用:

#parent img {
    width: inherit;
}