Centering with CSS + float attribute
Posted on 2007-08-12
I'm trying to use CSS to center a menu bar across the page. The problem is that the menu bar uses the float attribute to get the menus to line up properly. I thought I could do something like this:
<div style="width: auto; margin: 0 auto; text-align: center">
<ul style="display: block; margin: 0 auto">
<li style="display: block; float: left;">text1</li>
<li style="display: block; float: left;">text2</li>
However, this only results in all the <li> list items lining up in a single row (which is what I want) against the left border of the page (which isn't what I want). It looks like the problem is that "width: auto" attribute in the <div> tag, because the browser lets that element take up 100% of the page, instead of fitting it right around the <ul> element. When I put an actual value in there (i.e., "width: 500px"), I get the effect I'm looking for, but I'm told that's not a good practice to follow. So, how do I get the <div> tag to shrink to the right size (or is there some other hack I can employ)?