Karthikeyan sundaramoorthi Karthikeyan sundaramoorthi - 6 months ago 8
HTML Question

Why does float in the parent container alter an img's size?

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

Answer

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>

Comments