3

I have a container and a image inside it. When the parent is given float, there is a height mismatch in the child. When both are given float it matches. Why?

 <div class="parent"><img src="images/trest.png" class="image"></img></div>

Mismatches when:

.parent{
float:left;
}
.image{}

Perfect when:

.parent{
    float:left;
    }
    .image{
    float:left;
    }

enter image description here

Community
  • 1
  • 1
  • Works for me https://jsbin.com/galoso/edit?html,output – C14L May 19 '16 at 13:26
  • Do you maybe have a whitespace " " between `` and the closing ``? Also: there is no closing tag for ``. – C14L May 19 '16 at 13:29
  • 1
    It's not causing the issue but `` is invalid markup. `` should be a self-closing tag – andyb May 19 '16 at 13:30
  • 1
    It is because is a replaced element which has default vertical-align:baseline and baseline aligned elements reserve space for text descenders - see http://stackoverflow.com/questions/5804256/image-inside-div-has-extra-space-below-the-image – andyb May 19 '16 at 14:33

2 Answers2

3

Basically, specifying an element with float will in most cases make it into a block element.

Image elements by default are known to have the issue of unwanted white space underneath when placed in a block level container. The solution typically has been to set the image element's display to block.

From MDN:

As float implies the use of the block layout, it modifies the computed value of the display values in some cases:

Comparison between float and display: block (in essence, the results are the same):

.parent {
  float: left;
  border: 2px solid red;
}
.image {
  border: 2px solid blue;
}
.image2 {
  border: 2px solid blue;
  display: block;
}
.image3 {
  border: 2px solid blue;
  float: left;
}
<div class="parent"><img src="https://placehold.it/100x100" class="image"/></div>
<div class="parent"><img src="https://placehold.it/100x100" class="image2"/></div>
<div class="parent"><img src="https://placehold.it/100x100" class="image3"/></div>
timolawl
  • 5,434
  • 13
  • 29
0

andyb said in a comment on the question:

It is because <img> is a replaced element which has default vertical-align:baseline and baseline aligned elements reserve space for text descenders - see stackoverflow.com/questions/5804256/… – andyb

Because of this, another way to fix this is to set the vertical-align property to bottom instead of baseline.

From timolawl's answer, if you adjust the style of the first image to be:

.image {
    border: 2px solid blue;
    vertical-align: bottom;    /* added this */
}

then it will look the same as the other two, whish use display:block and float (respectively) to get the desired layout.

Community
  • 1
  • 1
Stephen P
  • 14,422
  • 2
  • 43
  • 67