Say I have this HTML:
<div class = "block1">hi</div>
<div class = "block2">hi</div>
And this CSS:
.block1 {
width:100px;
border:1px solid;
float: left;
}
.block2 {
width:100px;
border:1px solid;
}
Why does block2 need to have float:left; in order to be to the right of block1? Isn’t the property of block1 (float:left) enough?
block2is displayed as a block level element by default, which means it takes up a whole line.It doesn’t necessarily have to have
float:leftto show up on the right ofblock1; if it is displayed as an inline level element throughdisplay:inline, ordisplay:inline-block, it will appear next to its sibling.http://jsfiddle.net/8GF4B/1/
To explain it in further detail, let us imagine you had set
float:leftonblock2instead:The first thing that will happen is that block2 will be positioned where it would normally be positioned. Let’s find out where.
Now block2 is taken out of the normal flow, and shifted as far left as it can possibly be … but it is already against the left edge! This results in block2 showing up underneath block1.
Have a look here for a good explanation of the distinction between inline and block-level elements: https://developer.mozilla.org/en-US/docs/HTML/Block-level_elements