So what float
does is remove the element from the normal document flow. It exists so that when you have some text and (for example) an image that you want to sit in the text, you can apply float
to the image and anything that comes after it will flow around the image. Like so:
If you apply float to all the elements in your navbar, that means they are all removed from the document flow. So the container for them now effectively has no elements in, therefore it collapses. Your background colour is working fine, but because the element has nothing in it, it has no height, and because it has no height, you can’t see it.
With float, anything you put after floated elements is the thing that flows around those elements. It’s easier to see this visually:
So comment out the clear:both
. First, add some text before the nav items, like:
<ul>
hello
<li><a href="">Home</a></li>
<li><a href="">About Us</a></li>
The floated items are after that, so they are just removed from the document flow as before, they don’t sit on the background. But you can see your background is there, but just for that bit of text
Now move the text to after your nav items, like so:
<li><a href="">Portfolio</a></li>
<li><a href="">Blog</a></li>
<li><a href="">Contact</a></li>
hello
Now the text flows around the floated items (kinda)
They are still removed from the document flow, but because that text is flowing around them, the browser takes that into account for the size of the container that has your background colour applied.
Using clear
allows this to be “fixed”. clear
, when applied to an element, says “force this to move down to the next line”. That piece of text above, when put after the floated elements, actually did the same thing. So this:
&:after{
content: "";
display: block;
clear: both;
}
What it’s doing is creating an empty element in the CSS (so it will be invisible), and applying clear to it, forcing that empty element onto a new line. The browser now takes that into account, and the containing element does not collapse.
(I hope that was kinda understandable)
Note that this is all a hack first figured out in 2004 to get around CSS layouts being awful. The two actual CSS layout methods introduced in the last few years, Flex and Grid, completely remove the need for using floats for layout. But there is a lot of code around that uses floats because it was the best option for ~10 years, so I think it is important to know how it works.