Reputation:
I noticed that inline-blocks and blocks behave differently when they are situated near a floated element : background of blocks extends under the floated element while inline-blocks wrap it entirely.
div
is a block :
div {
height: 5em;
width: 5em
}
div:first-child {
background: #27A5CC;
float: left
}
div:nth-child(2) {
width: 6em;
background: #EEEEEE
}
div
is an inline-block :
div {
height: 5em;
width: 5em
}
div:first-child {
background: #27A5CC;
float: left
}
div:nth-child(2) {
width: 6em;
background: #EEEEEE;
display: inline-block
}
Is there an explanation for it?
Upvotes: 0
Views: 333
Reputation: 272436
I will assume that you understand the difference between block
and inline-block
displays. Let us now look at how floats
work:
A float is a box that is shifted to the left or right on the current line. [...] Content flows down the right side of a left-floated box and down the left side of a right-floated box.
A floated box is shifted to the left or right until its outer edge touches the containing block edge or the outer edge of another float. If there is a line box, the outer top of the floated box is aligned with the top of the current line box. [...]
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. However, the current and subsequent line boxes created next to the float are shortened as necessary to make room for the margin box of the float.
Your examples explained below:
Example 1
The first div is floated. It is taken out of the flow and aligned with left side of the parent. The second div also starts from left side ignoring the first div as if it did not exist.
Result: both divs end up with their top-left corners aligned with each other.
Example 2
The first div is floated. It is taken out of the flow and aligned with left side of the parent. The second div is an inline block element, therefore it follows the rules that apply to content flow and line boxes. It starts rendering towards the right side of first div just as normal text would.
Result: the second div aligns with the right side of first div.
Upvotes: 2