A CSS Note On Combination of Float and Overflow
The code snippet below, will generate a navigation bar like the one above.
CTYPE html> <html> <head> <style> ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: #333; } li { float: left; } li a { display: inline-block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; } li a:hover { background-color: #111; } .active { background-color: red; } </style> </head> <body> <ul> <li><a href="#home" class="active">Home</a></li> <li><a href="#news">News</a></li> <li><a href="#contact">Contact</a></li> <li><a href="#about">About</a></li> </ul> </body> </html>
If you remove the "overflow: hidden;" part from the CSS the navigation bar will disappear!(except the home link!)
This article aims to explain that behavior.
First
<li> is a block-level HTML element! that is, each li would locate itself in a newline and won't allow other elements to sit beside it. But this is not what we are seeing in the picture above! each navigation link is a <li> element and they are all in the same row!
To change the default behavior of block-level elements float css property can used! (as is used in out case)
Second
A container, whose inner elements are floated, won't resize its height, in order to cover its content. Instead, the inner element simply overflows outside of its container! (Notice how the image has overflowed the green border. That border belongs to a div containing the image!)
To fix this problem one approach is to use the overflow css property. Lets add the overflow: auto; to the style of the containing div and see what happens:
Now that we know these stuff let's go back to our problem.
Third
In that snippet, the <ul> is actually the container whose inner elements are floating! So the overflow: hidden; is there to force the container tag, which is a ul tag in our case, to resize its height according to its inner elements!
When you remove that part of css, the dimensions of the space allocated to that tag is something like: 597x0. Note that the height is ZERO! literally zero! meaning no space is allocated in fact.
The area whose background color is black, after removing the overflow property, shrinks to become nothing. Font-color in that snippet is white, hence it can not be seen if the background color is white too. And this is why the whole thing seems to be vanished.
Dreamer, Founder and CEO, CrystaCode
5 年Thank you. It was really helpful.