So i was examining the css float property when i noticed a strange behavior that i couldn’t know its reason.
This is a link to the code and preview of four divs, first two are floated right and left, third and forth just a normal divs.
I do understand that the third div will get overlapped by the second one, however what i don’t understand is why the content of the third div got shifted down, shouldn’t it hide behind the second div?
P.S i know the problem can be fixed using the clear property for the third div, however i am more concerned about the reason behind this behavior.
Code:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
aside, article, section, header, footer, nav {
display: block;
}
html, body {
margin: 0;
padding: 0;
}
html {
background: #ccc;
}
body {
width: 600px;
background: #fff;
margin: 2em auto 2em;
font: 100% Arial, Helvetica, sans-serif;
}
div {
margin-bottom: 1em;
margin-right: 2em;
width: 85px;
height: 50px;
border: 1px solid #000;
padding: 25px;
}
/*add styles here*/
.element1 {
background: rgb(26, 78, 175);
float:right;
color:white;
}
.element2 {
background: rgb(85, 66, 54);
float:left;
color:white;
}
.element3 {
background: rgb(247,120,37);
}
.element4 {
background: rgb(211, 206, 61);
}
?
</style>
</head>
<body>
<div class="element1">Element 1 floated right</div>
<div class="element2">Element 2 floated left</div>
<div class="element3">Element 3 normal flow</div>
<div class="element4">Element 4 normal flow</div>
</body>
</html>
I’ve found the answer to my question within this document.
Quoting from the document:
So basically what the document says is, floated elements can overlap the Box model of elements added to the document normal flow, however it can’t overlap their content; in other words, content of an overlapped element is restricted to the non-overlapped space.
P.S. So far i have abstracted the floating behavior as such:
Element1: floated element
Element2: non-positioned element
1-Draw Element2’s box model.
2-Draw the Element1’s box model and its content.
3-If Element2 still has non-overlapped space start filling it with its content.
4-If the space couldn’t hold the whole content, start appending them under Element2 box model.
Hope this would help.
Btw, thanks and +1 to everyone who contributed to the question.