Today is Floats and even though I know the basics, I wanted to understand it better.
I started digging into A List Apart article and wanted to write down my understanding of what I read.
To understand Floats is to understand the normal flow of element and how the
float property changes the behavior of that element.
For example we have block level elements such as
p. They always take the full width of the page. Once you apply the
float property, they start behaving like inline elements such as
img. Quick reminder, inline elements only takes as much space as their content.
Quick Note About Floats
Once you use the
float property, it's almost like using the universal selector. This property will be applied to the rest of the elements. This means that other elements will be out of their normal flow as well whether you applied the
float property to them.
The solution is to clear the float and you do so with the
clear property. There are five available values:
See a good explanation and example here
Placement of your Floated Elements in HTML
One of the new things I learned was how the placement of your floated element in HTML can contribute to the float not working property and setting it out of the container you put it.
If the floated elements is set before the non floated element, you run the risk of having the floated element get out of the container.
This happens because of something called collapsing which essentially means that since the floated element is not in the normal, the parent element (the container) is behaving as if the element is not there.
One solution to this is to add an inline CSS in the HTML to clear the float. That adds extra markup in the page and that is not the ideal fix.
Another solution is to add an overflow to the parent element (the container) and set it to
overflow:hidden. As this property was not meant for this purpose, there are risks such as scrollbars and hidden items. You can find more about it here and here
Last solution is to use the pseudo selector
::after with the parent container and adding the
clear property there.
I starting to enjoy writing these, I learn so much better when I try to think of a way to explain what I just read or watched.
The streak continues...