When I first learned HTML, I was told that if you want to float 2 divs side by side using float:left
, you must set a width on those two elements. This is because a div, by default, is a block element, which will take up the full width it has available to it.
As I've built various projects, I have come across cases where floating did not work without setting a width, but then in other cases, it seems a width is not needed, and the float itself will restrict the elements width.
For example, the following fiddle shows two elements floating side by side only using the float property, no width was required.
<style>
.left{
background-color:yellow;
float:left;
}
.right{
background-color:green;
float:left;
}
</style>
<div class="left">
Floating left
</div>
<div class="right">
Floating left
</div>
However, in other similar scenarios that I can't seem to reproduce right now, applying the float property to two divs
does not allow them to float side by side unless a width is a set for both.
Am I losing my mind or is there some scenarios for which this behavior varies?
When set float:left
or float:right
on an element, it forces the creation of a new block formatting context, and it behaves similarly to inline block level, the width and height are dynamic (determined by the content).
... a block element, which will take up the full width it has available to it.
A non-replaced block element in normal flow will take up the full width it has available to it. This requirement is stated at http://www.w3.org/TR/CSS2/visudet.html#blockwidth
A floated element is not in normal flow, so that rule does not apply. Instead, float widths are determined according to their own rules, stated and described at http://www.w3.org/TR/CSS2/visudet.html#float-width. This says that when a floated element has a computed width of "auto", its used width is determined using the shrink-to-fit algorithm.
Note that the shrink-to-fit algorithm is also used for other types of layout, including non-replaced inline-block elements and table cells, but in other respects, such as vertical alignment, the layout behaviour of those elements is quite different from that of floats.
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