【问题标题】:Scale Image to Div With Inherited Height使用继承的高度将图像缩放到 Div
【发布时间】:2015-02-05 13:48:25
【问题描述】:

我想将 png 图像适合从另一个 div 继承其高度的 div 的高度。我已经看到如何通过将图像的最大高度设置为 100% 来完成此操作(在诸如此类的问题中:How do I auto-resize an image to fit a div container),但这仅在图像直接位于高度以像素为单位的 div 中时才适用.

我有一个 topbar,我明确设置了它的高度,还有一个 logodiv,它继承了 topbar 的高度。但是,除非我明确设置高度(注释代码),否则徽标不会调整大小以适应 logodiv 的高度。

当它应该被继承时,必须设置两次高度似乎是糟糕的编码。有没有办法在不这样做的情况下将图像调整到正确的高度?

css:

#topbar{
    width:100%;
    height:45px;
}
#logodiv{
    float:left;
    /* height:45px; */
}
#logodiv img{
    max-height:100%;
}

html:

<div id="topbar">
  <div id="logodiv">
    <img src="images/project/logo.png" />
  </div>      
</div>

【问题讨论】:

    标签: html css


    【解决方案1】:

    我想让 png 图像适合 继承的 div 的高度 它与另一个 div 的高度。

    从技术上讲,logodiv不会topbar 继承其高度。它只是根据其内容(本例中的图像)扩展自身。

    尝试将属性 height:inherit; 添加到第二个 div 中,一切顺利。

    HTML

    <div id="topbar">
      <div id="logodiv">
        <img src="images/project/logo.png" />
      </div>      
    </div>
    

    CSS

    #topbar{
        width:100%;
        height:45px;
    }
    
    #logodiv{
        float:left;
        height:inherit;
        /* height:45px; */
    }
    
    #logodiv img{
        max-height:100%;
    }
    

    Fiddle

    【讨论】:

    • 没有height: inherit 有没有办法做到这一点?有时,在具有高度的元素与希望为该高度的内部元素之间存在多于 1 个元素。将height: inherit 放在整个层次结构的每个元素上似乎不太好。
    【解决方案2】:

    试试这个 CSS:

    #topbar {
        width:100%;
        height:45px;
        border:1px solid red;/* for highlighting*/
    }
    #logodiv {
        float:left;
        height:inherit;
    }
    /*To clear float */
    #topbar:after {
        clear:both;
        display:block;
        content:""
    }
    #logodiv img {
        max-height:100%;
    }
    

    演示:http://jsfiddle.net/lotusgodkk/4d4L1g0a/

    【讨论】:

      猜你喜欢
      • 2012-06-05
      • 1970-01-01
      • 1970-01-01
      • 2020-03-01
      • 1970-01-01
      • 2020-11-10
      • 2016-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多