2

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>
Community
  • 1
  • 1
Matt Cooper
  • 2,042
  • 27
  • 43

2 Answers2

4

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

nalinc
  • 7,375
  • 24
  • 33
  • Is there a way to do this without `height: inherit`? There are times when there is many more than 1 element in between the element with the height, and the inner element which is desired to be that height. And it seems not great to put `height: inherit` on every element throughout the hierarchy. – tscizzle Jun 06 '16 at 03:48
1

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

Demo : http://jsfiddle.net/lotusgodkk/4d4L1g0a/

K K
  • 17,794
  • 4
  • 30
  • 39