Reputation: 6132
I am trying to put a list inside of a <div>
so that I can change the background of the div and make the list be a navbar.
The problem is that the items in the list actually appear in a horizontal row below the div. I don't know why this is - they are child elements and should float to the left of each other inside the <ul>
element which is inside the <div>
, or at least that's my understanding of it.
When I remove float: left
, they work fine, but appear in list format instead of side by side like I want.
Why is this occuring?
Here is the PHP code that creates the HTML.
echo <<<_HDOC
<div id="header">
Title
</div>
<div id="linkbar">
<ul id="links">
_HDOC;
if ($_COOKIE['main'] == "")
echo "<li class='menulinks'>Register</li> <li class='menulinks'>Login</li>";
else{
$cookieparts = explode('&', $_COOKIE['main']);
echo "<li class='menulinks'>Welcome $cookieparts[0]</li> <li class='menulinks'>Logout</li>";
}
echo "<li class='menulinks'>About</li> </ul></div>";
And here is the CSS code
#linkbar{
padding: 5px;
background-color: #31574A;
color: white;
}
#links{
width: 100%;
list-style-type: none;
}
.menulinks{
float: left;
padding: 10px;
}
Upvotes: 3
Views: 2832
Reputation: 6664
An easy solution (that doesn't require adding new elements) is to simply add overflow:hidden;
to the element containing the floated elements.
Upvotes: 0
Reputation: 3194
Floated elements don't push their containers by default.
You should research css clearfix.
In your example, maybe something like this will do the trick:
#links:after {
content: "";
display: table;
clear: both;
}
Try it with that!
Regards.
Upvotes: 0
Reputation: 50475
You need to add a clear
to at the end of the list.
Why do I have to do this?
A container element's height does not automatically adjust to a child element that is floated. When something is floated, it is removed from the traditional flow. In order to resolve it, you must use a clear
CSS
li
{
float: left;
}
.clearFix
{
clear: both;
}
HTML
<div class="container">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<div class="clearFix"></div>
</div>
Upvotes: 2