缩放div中的图像失败

时间:2014-10-17 17:36:39

标签: html css

我在HTML中有以下结构:

<div id="a">
    <div id="b">
        <div id="c">
            <img src="http://public.media.smithsonianmag.com/legacy_blog/npg_portraits_nicholson_jack_2002.jpg"/>
        </div>
    </div>
</div>

在CSS中:

#a{
    height: 300px;
    background-color: red;
    padding: 20px;
    width: 100%;
    text-align:center;
}

#b {
    width: auto;
    height: auto;
    display: inline-block;
    max-height:100%; /*should be 300px - 2*20px = 260px */
    /*no height shall be set here*/
}

#c {
    background-color:green;
    max-width: 300px;
    max-height: inherit;
}

img {
    opacity: 0.8;
    max-width: 100%;
}

我希望将图像缩放到红色容器中。结构是那种固定的方式。我还为你上传了小提琴:

Demo Fiddle

我希望有人能够提供帮助!

1 个答案:

答案 0 :(得分:2)

在图片上按position: absolute缩放。

  • #aposition: relativeposition: absolute图片会相应缩放。

  • 以top,right,bottom,left和margin: auto

  • 的组合为中心
  • box-sizing: border-box将填充和任何边框合并到您的宽度中,有助于防止令人讨厌的滚动条

实施例

&#13;
&#13;
* {
  box-sizing: border-box;
}
#a {
  height: 300px;
  background-color: red;
  padding: 20px;
  width: 100%;
  text-align: center;
  position: relative
}
#b {
  width: auto;
  height: auto;
  display: inline-block;
  max-height: 100%;
  /*should be 300px - 2*20px = 260px */
  /*no height shall be set here*/
}
#c {
  background-color: green;
  max-width: 300px;
  max-height: inherit;
}
img {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  opacity: 0.8;
  height: 90%;
  height: calc(100% - 40px);
}
&#13;
<div id="a">
  <div id="b">
    <div id="c">
      <img src="http://public.media.smithsonianmag.com/legacy_blog/npg_portraits_nicholson_jack_2002.jpg" />
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

相关问题