0

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?

Cirrus
  • 105
  • 8
  • 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 Answers2

1
  1. If you unset float for box 3 it will go back to the left.
  2. 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)
  3. 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>
Chaska
  • 3,165
  • 1
  • 11
  • 17
1

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.

For example Float behaviour

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?

Float behaviour with blocks of same width and height

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.

Float behaviour with a larger box wrapping

And so what will happen in your case?

Float final layout

Yes, box 3 will go behind box 1 and everything else is laid out accordingly.

Pankaj Phartiyal
  • 1,691
  • 1
  • 12
  • 23