Simple (noob) HTML/CSS question

Associate
Joined
11 Jun 2009
Posts
1,249
Been messing around with HTML/CSS, and I'm having problems.
Basically, I'm trying to make a horizontal menu bar. No problem there. Now, when I try to change the background colour of the menu to #333, nothing happens.

HTML:
Code:
<div id="navigationbar">
	<ul>
		<li><a href="/index.php">Home</a></li>
		<li><a href="/practise/practise.php">Practise pages</a></li>		
		<li><a href="/old/index.php">Old stuff</a></li>
	</ul>
</div>
CSS:
Code:
#navigationbar {
	background: #333;
	width: 100%;
	margin: 0;
	padding: 0;
}

#navigationbar ul {
	list-style: none;
	padding: 0;
}

#navigationbar li {
	float:left;
}

#navigationbar a {
	display: block;
	padding: 8px 12px;
}

I take it I'm missing something silly, but I can't see what :(
 
The problem is because your LIs are floated, they are taken out of the standard document flow, so their containing elements have no height.

To fix this you can either

1) Set a fixed height on your #navigationbar. 36px is right at the mo, although this will change per browser, and if you amend the line-height. It also won't work if an LI spans 2 lines.
2) Use clearfix.

Here's a fiddle to show you the basic way of doing the second method.
 
Last edited:
Alternatively, you can apply overflow: hidden on #navigationbar. (overflow clears floats as well, but requires a set width, which you already have, and can't be used if you actually require overflow, which is seldom)

Also, do you really need the containing div, or could you not simply put the id on the ul?
 
Thanks, that makes sense now!
I'll get rid of the containing div too, not sure why I'm using that.

I think I need to re-read a CSS tutorial though :P
Page layout with floats seems to be a bit harder than I thought.
 
I'll get rid of the containing div too, not sure why I'm using that.
Page layout with floats seems to be a bit harder than I thought.

You're using the container div because one of the first things you learn is that you have to put everything into containers so you just do it without realising that a ul is already self contained really.

Floats become a piece of cake once you figure out clearing. I used to float absolutely everything when I was first learning as it seemed easier. I just make sure to put the floats in a container and clear them now.
 
don't forget you can use the new html5 <nav> element as the container is you want.

Code:
<nav id="navigationbar">
	<ul>
		<li><a href="/index.php">Home</a></li>
		<li><a href="/practise/practise.php">Practise pages</a></li>		
		<li><a href="/old/index.php">Old stuff</a></li>
	</ul>
</nav>
 
Back
Top Bottom