Can anyone tell me why do the block level elements given float property does behave oddly? I want to understand what actually happens to an element[block or inline] when we give a float property.
Below is the code and fiddle:
<div class="container violet">
<div class="float red">float</div>
<div class="foo blue">foo</div>
<div class="bar green">bar</div>
<div class="baz orange">baz</div>
</div>
CSS
.float {
float: left;
}
.foo {
padding-top: 10px;
}
.bar {
width: 30%;
}
.baz {
width: 40%;
}
.violet{
background-color: violet;
}
.red{
background-color: red;
}
.blue{
background-color: blue;
}
.green{
background-color: green;
}
.orange{
background-color: orange;
}
http://jsfiddle.net/gcazev14/
My curosity, it is still in the normal flow but its now positioned inside the foo[blue] block
A Block-level element occupies the entire horizontal space of its parent element (container), and vertical space equal to the height of its contents, thereby creating a "block". Browsers typically display the block-level element with a newline both before and after the element.
A floating element is one where the computed value of float is not none . As float implies the use of the block layout, it modifies the computed value of the display values, in some cases: Specified value. Computed value. inline.
Examples of block level elements: <p> <ol> , <ul> , <dl> All headings.
Difference Between Inline and Block Elements in HTMLInline elements never start from a new line. Block elements cover space from left to right as far as it can go. Inline elements only cover the space as bounded by the tags in the HTML element. Block elements have top and bottom margins.
It is because the original intended purpose of floats was not to put block elements side by side, but to reproduce the traditional typographical effect of wrapping text around images and boxouts as seen in this diagram from the CSS 2 spec.
There are various workarounds, but you'd probably be better off with display: inline-block
, flexbox or CSS grids if you want side-by-side blocks.
When you float an element it takes it out of the normal flow. If you inspect it's parent without any other siblings, the parent element will not have a height. The floated element actually punches through the bottom of its parent.
Floating an element also makes its width collapse to the width of its content (if any). That means, if it has no content, it'll be 0 width. So, if you want it to have a certain width, you have to set that.
If you want the parent to contain it, you'll either need a sibling element to clear the float with "clear: both" or you'll need to do something like bootstrap does with ".clearfix" (Understanding Bootstrap's clearfix class)
Depending on how you want the floated element’s siblings to interact with it, you may also need to float them.
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