Styling li tags with float:left is a standard way to create horizontal navigation bars. But whenever I do this, the entire navigation bar list gets separated from the containing div.
Removing float:left would fix the problem, but let’s assume I want to do it this way.
HTML
<html>
<head>
<link rel="stylesheet" type="text/css" href="temp.css" />
</head>
<body>
<div id="header">
<h2>Demo: Navigation Bar</h2>
<ul id="navbar">
<li>
<a href="#">News</a>
</li>
</ul>
</div>
</body>
</html>
CSS
#header {
margin: 10px;
width: 8in;
background-color: green;
margin-left: auto; /* setting margin to auto centers block element */
margin-right: auto; /* width must not be 100% */
}
#header ul { /* ul */
list-style-type: none;
padding: 0;
margin-top: 0px;
}
#header li {
display:block;
float:left;
background-color: silver;
margin: 0;
}
Any insight is much appreciated!
Edit:
Solution is to add empty div after the list, or style the containing div with overflow:hidden.
After looking for an explanation why this happens, I found a great link explaining everything!
The trick is, working with float’s – use clearfixes. In your case, add the following, before header closing tag
</div>:That will make header strech, considering floating elements inside it.