Cody Cody - 18 days ago 5
CSS Question

CSS - unexpected floating issue

I am learning floating elements in CSS and i encountered the following peculiar behavior.

Here is the code



<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>

#one { background-color: red; width: 200px; height: 200px; margin: 10px; }
#two { background-color: yellow; width: 200px; height: 205px; margin: 10px; }
#three { background-color: lightpink; width: 200px; height: 200px; margin: 10px; }
#four { background-color: green; width: 200px; height: 200px; margin: 10px; }
#five { background-color: coral; width: 200px; height: 200px; margin: 10px; }
#six { background-color: #b1ffea; width: 200px; height: 200px; margin: 10px; }

div{
/*display: inline-block;*/
float: left;
vertical-align: central;
}


</style>

</head>
<body>

<div id="one">
First div
</div>

<div id="two">
Second div
</div>

<div id="three">
three div
</div>

<div id="four">
four div
</div>

<div id="five">
five div
</div>

<div id="six">
six div
</div>

</body>
</html>





enter image description here

My question is why "four div" is placed below the "third div" not first and second ?

On the other hand, if i resize the browser (see image below) why in this case it is working perfectly ?

enter image description here

Answer

Because the second div element is taller than the first div, the forth div collides with the second div. When the forth div drops to the next line, it starts on the right and slides left, beginning under the third div, until it collides with the second div. If you look at your code at with 4 div elements per line, the fifth div drops to the next line. It begins below the fourth div and beginning moving left until it collides with the second div, because the second div is longer that the third or fourth div elements.

enter image description here

Comments