使用继承的高度将图像缩放到Div(Scale Image to Div With Inherited Height)

编程入门 行业动态 更新时间:2024-10-28 02:25:20
使用继承的高度将图像缩放到Div(Scale Image to Div With Inherited Height)

我想适合一个PNG的高度,从另一个div继承其高度的PNG图像。 我已经看到了如何通过将图像的最大高度设置为100%来完成这项工作(例如: 如何自动调整图像的大小以适合div容器 ),但这只适用于当图像是直接在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>

I want to fit a png image to the height of a div that is inheriting its height from another div. I have seen how this can be done by setting the image's max-height to 100% (in questions such as this: How do I auto-resize an image to fit a div container), but this only works for me when the image is directly in the div thats height is specified in pixels.

I have a topbar, whose height I set explicitly, and a logodiv inside that, which inherits the height from the topbar. However, the logo does not resize to fit the height of logodiv unless I explicitly set the height (the commented code).

It seems like bad coding to have to set the height twice, when it should be inherited. Is there any way to fit the image to the correct height without doing this?

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>

最满意答案

我想适合一个PNG的高度,从另一个div 继承其高度的PNG图像。

从技术上讲, logodiv 不是从logodiv继承它的高度。 它根据其内容(本例中的图像)简单地扩展自己。

尝试添加属性height:inherit; 到第二格,你很好去。

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%; }

小提琴

I want to fit a png image to the height of a div that is inheriting its height from another div.

Technically, logodiv is not inheriting its height from topbar. Its simply expanding itself according to its content(the image in this case).

Try adding the property height:inherit; to second div and you are good to go.

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,高度,div,logodiv,电脑培训,计算机培训,IT培训"/> <meta name="descrip

本文发布于:2023-08-06 03:02:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1443980.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:缩放   图像   高度   Div   Height

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!