html - 使用继承高度将图像缩放到 Div

标签 html css

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

我有一个顶栏,我明确设置了其高度,并且其中有一个 logodiv,它继承了顶栏的高度。但是,除非我明确设置高度(注释代码),否则 Logo 不会调整大小以适合 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>

最佳答案

I want to fit a png image to the height of a div that is inheriting its height from another 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

关于html - 使用继承高度将图像缩放到 Div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28336795/

相关文章:

javascript - 如何为此代码添加模态窗口参数?

html - IE 9 CSS 问题 : height css attribute issue

css - 垂直对齐的对齐问题

jquery - 当高度大于容器时,div 追加问题

html - 使用 CSS 显示加载图像

javascript - 如何在 Thymeleaf 中将 javascript 文件内容嵌入到 html 页面中?

javascript - 在 div 中打开一个 anchor 链接

html - 如何使文本框适合带有标签的父 DIV?

javascript - 如何制作标签菜单

html - 间隙属性表明它在 MDN 上不受支持。使用安全吗?