I am a novice in css and got a problem when I learned the behavior of float from MDN website https://developer.mozilla.org/en-US/docs/Web/CSS/float. I tried CodePen example on the above website and commented out line 17 in the css file. The result I got is that the blue box seems magically disappear. My guess is that there is something wrong with border collapsing. Can anyone point me in the right direction and explain what's going on there?
-
check [this answer - read section Block Formatting Context (BFC)](https://stackoverflow.com/questions/39920386/block-formatting-contexts-collapsing-margins-and-floating-containers/39923386#39923386)... quoting from there: *The floated elements are reinserted into the BFC while rendering around the element that is not floated* – kukkuz Sep 12 '18 at 05:31
2 Answers
- If you unset
float
for box 3 it will go back to the left. - You cannot see it because the box 1 has
float: left
and covers it. Try making box 1 transparent to have box 3 appears. (Refer to the snippet below) - Content of box 3 will be pushed to next line because box 1 occupied the very left position.
Correct me if any mistakes. Thanks.
section {
border: 1px solid blue;
}
div {
margin: 5px;
width: 50px;
height: 50px;
}
.left {
float: left;
background: pink;
}
.right {
/* float: right; */
background: cyan;
}
<!-- Learn about this code on MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/float -->
<section>
<div class="left" style="opacity:0;">1</div>
<div class="left">2</div>
<div class="right">3</div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Morbi tristique sapien ac erat tincidunt, sit amet dignissim
lectus vulputate. Donec id iaculis velit. Aliquam vel
malesuada erat. Praesent non magna ac massa aliquet tincidunt
vel in massa. Phasellus feugiat est vel leo finibus congue.
</p>
</section>

- 3,165
- 1
- 11
- 17
Its because the box 3 is now behind box 1.
What float means is, any content after the element will wrap in the opposite direction and also its flow will be reset i.e. it will start from the point where it should have been placed when the float element is removed from DOM.
As you can see the actual position of the paragraph starts from the initial position of 1.
What will happen when there is a block element of the same width and height instead of the paragraph?
Exactly!! It will go behind box 1. Why 3 is below 1? Because there is no space on the right. If we increase the box 3 width then it will wrap on left accordingly.
And so what will happen in your case?
Yes, box 3 will go behind box 1 and everything else is laid out accordingly.

- 1,691
- 1
- 12
- 23
-
For the second figure you showed, why the number 3 appears below block 1 instead of behind block 1? – Cirrus Sep 12 '18 at 14:34
-
1see figure 1, the child nodes in this case the text node never goes behind, it wraps within available space. – Pankaj Phartiyal Sep 12 '18 at 14:40