Search code examples
htmlcssimagecss-float

Floating a div with image results in extra space


I have a div which floats left. Inside the div, I have an image. Following the diff is a paragraph.

I expect the paragraph to wrap around the image but I am seeing plenty of white space.

.class-0-568 {
  float: left;
}

.class-0-569 {
  padding-right: 2%;
  width: 33%;
}

.class-0-570 {
  line-height: 1.2em;
  margin-top: 0.2816004em;
}
<div class="class-0-568" id="id-0-553">
  <img alt="" class="class-0-569" id="id-0-554" src="https://i.postimg.cc/BZYZRfKP/image-0-4.jpg">
</div>
<p class="class-0-570" id="id-0-555">These offer a description of who you are</p>

Here is the output of above

Output

If I set the float property to img, then it is working as expected.

Correct Output

I dont understand why. Can someone please help me?

PS: JSFiddle link if anyone wants to play:

https://jsfiddle.net/chid1989/say7pzqe/#&togetherjs=z8iIlaQmNz

EDIT

I tried inspecting the elements through chrome. Apparently, the div is occupying the extra space. But I dont know why.

Inspection


Solution

  • Your images width (caused by its class .class-0-569) is 33%. But that's of its container / parent element, i.e. the floated .class-0-568 element.

    Apply the 33% width to the image's parent (.class-0-568) and 100% width to the image itself:

    .class-0-568 {
      float: left;
      width: 33%;
    }
    
    .class-0-569 {
      padding-right: 2%;
      width: 100%;
      height: auto;
    }
    
    .class-0-570 {
      line-height: 1.2em;
      margin-top: 0.2816004em;
    }
    <div class="class-0-568" id="id-0-553">
      <img alt="" class="class-0-569" id="id-0-554" src="https://i.postimg.cc/BZYZRfKP/image-0-4.jpg">
    </div>
    <p class="class-0-570" id="id-0-555">These offer a description of who you are</p>

    Addition after comments: The - actually much simpler - alternative is to float the image itself without using a wrapper div:

    #id-0-554 {
      float: left;
      width: 33%;
      margin-right: 2%;
    }
    
    
    .class-0-570 {
      line-height: 1.2em;
      margin-top: 0.2816004em;
    }
     <img alt="" class="class-0-569" id="id-0-554" src="https://i.postimg.cc/BZYZRfKP/image-0-4.jpg">
    <p class="class-0-570" id="id-0-555">These offer a description of who you are</p>