JSFiddle Link: here
div{
width:50px;
height:20px;
}
#container{
border:5px solid black;
width:400px;
height:200px;
}
#a{
background-color:red;
float: left;
}
#b{
background-color:blue;
float: left;
clear: left;
}
#c{
background-color:green;
float: right;
}
#d{
background-color:orange;
float: right;
clear: right;
}
#e{
background-color:black;
float: right;
clear: right;
}
<div id="container">
<div id="a">
</div>
<div id="b">
</div >
<div id="c">
</div>
<div id="d">
</div>
<div id="e">
</div>
</div>
Following image is the end result, Where you can see that, the elements on the right are not starting from the top position. There is a 1 brick space at the top. Why is that ? What is the logic ?
If you are using float alone, without specifying positions/margins, you'll have to rely on the browsers way of piling / blocking stuff together.
A work around in your code would be changing the C
element order, so it can pile in a proper position (like putting together a bunch of lego blocks):
<div id="a"></div>
<div id="c"></div>
<div id="b"></div>
<div id="d"></div>
<div id="e"></div>
Floats do not automatically go to the top of the container. The Red element takes his place on the left. The Blue element floats to the left as well, but it's cleared on the left, so it's pushed to the next line. Then you have the Green element with float right, since Blue is cleared on the left, not on the right, it takes the place on the right on the same line.
In short, it floats where it should on the closest availible spot, not at the top-most one.
I hope I'm being clear enough, but if it is still confusing, please, let me know.
Clear
plays no direct part in this rule, and is simply affecting the position of the second left floated div, from which the first right floated div takes its position.
For example, the same 1 brick space appears if the second floated left div is on a second line for other reasons, such as if the width of the first two divs exceeds 100%.
div{
width:30%;
height:20px;
}
#container{
border:5px solid black;
width:400px;
height:200px;
}
#a{
background-color:red;
float: left;
width:60%;
}
#b{
background-color:blue;
float: left;
width:45%;
}
#c{
background-color:green;
float: right;
}
#d{
background-color:orange;
float: right;
clear: right;
}
#e{
background-color:black;
float: right;
clear: right;
}
<div id="container">
<div id="a">
</div>
<div id="b">
</div >
<div id="c">
</div>
<div id="d">
</div>
<div id="e">
</div>
</div>
Step 5 in the CSS2.2 rules for floats says:
The outer top of a floating box may not be higher than the outer top of any block or floated box generated by an element earlier in the source document.
So the highest place that the first right floated div can be is level with the second left floated one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With