Robert
Robert

Reputation: 10390

CSS Float not wrapping 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 is the orange and green boxes not wrapping and instead appearing underneath? According to my understanding if there is enough space the elements will surround the float and move underneath it, not behind it.

I am aware of the clearfix solution of <div style="clear: both"></div> but do not understand why the above is happening.

https://jsfiddle.net/ap5ugv8s/

I would've expected the above from an absolutely positioned element, not a float.

Upvotes: 4

Views: 2701

Answers (2)

Rob
Rob

Reputation: 15160

Let's see if I can word this correctly. Floated elements, as you know, are not in the normal flow. While floated elements will line up against each other, to other block elements it's as if they aren't there at all. This means they will be placed over the floated elements if they are not positioned, such as position:relative;. You can try adding that to some of your non-floated divs to play with and see how adding positioning changes things. Positioning of the elements is the key phrase.

I may edit this some more in the morning when I wake up but you may want to read the W3C's explanation in the spec.

Since a float is not in the flow, non-positioned block boxes created before and after the float box flow vertically as if the float did not exist.

Upvotes: 1

Oriol
Oriol

Reputation: 288200

That's because blocks with overflow: visible that follow a float behave like this:

enter image description here

To fix it, you can set overflow: hidden. Then it will behave like this:

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>

Upvotes: 3

Related Questions