CSS Float doesn't wrap around

HTML:

<div class="block pink float"></div> <div class="block blue float"></div> <div class="block green"></div> <div class="block orange"></div> 

CSS

  .block { width: 200px; height: 200px; } .float { float: left; } .pink { background: #ee3e64; } .blue { background: #44accf; } .green { background: #b7d84b; } .orange { background: #E2A741; } 

Why don't the orange and green boxes wrap around and instead appear below? According to my understanding, if there is enough space, the elements will surround the float and move under it, and not behind it.

I am aware of the clearfix <div style="clear: both"></div> solution, but I don’t understand why this is happening.

https://jsfiddle.net/ap5ugv8s/

I would expect this to be from an absolutely positioned element, not a floating one.

+4
source share
3 answers

This is because the blocks with overflow: visible that follow the float behave as follows:

enter image description here

To fix this, you can install overflow: hidden . Then it will behave as follows:

enter image description here

 .block { width: 200px; height: 200px; overflow: hidden; } .float { float: left; } .pink { background: #ee3e64; } .blue { background: #44accf; } .green { background: #b7d84b; } .orange { background: #E2A741; } 
 <div class="block pink float"></div> <div class="block blue float"></div> <div class="block green"></div> <div class="block orange"></div> 
+1
source

Let's see if I can formulate this correctly. Floating elements, as you know, are not in a normal flow. While the floating elements will line up against each other, the other elements of the block, as if they were not there at all. This means that they will be placed above the floating elements if they are not located , for example position:relative; . You can try adding this to some of your non-floating divs to play around and see how adding positioning changes the situation. Positioning elements is a key phrase.

I can change this in the morning when I wake up, but you can read the W3C explanation in the spec.

Since the float is not in the stream, blocks are created with non-positioned blocks before and after the flow of float boxes vertically, as if the float did not exist.

+1
source

Not if it's block . What happens is the floats curled up on top of the block elements. And the blocks are stacked on top of each other. I would use inline-block instead to get the wrapping using float.

 .block { width: 200px; height: 200px; display: inline-block; } 

https://jsfiddle.net/ap5ugv8s/2/

0
source

All Articles