Home > Software design >  Floating a div with image results in extra space
Floating a div with image results in extra space

Time:03-29

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  id="id-0-553">
  <img alt=""  id="id-0-554" src="https://i.postimg.cc/BZYZRfKP/image-0-4.jpg">
</div>
<p  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

CodePudding user response:

<div> and <p> are both block level elements. The correct way to float images in text is to place the <img> directly inside the <p>:

<html>
<head>
<style>
.class-0-569 {
  padding-right: 2%;
  width: 33%;
  float: left;
}

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

Fiddle

CodePudding user response:

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  id="id-0-553">
  <img alt=""  id="id-0-554" src="https://i.postimg.cc/BZYZRfKP/image-0-4.jpg">
</div>
<p  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=""  id="id-0-554" src="https://i.postimg.cc/BZYZRfKP/image-0-4.jpg">
<p  id="id-0-555">These offer a description of who you are</p>

  • Related