• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1356
  • Last Modified:

Centering with CSS + float attribute

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>
      etc.
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)?

Thanks.
0
tjgquicken
Asked:
tjgquicken
  • 2
1 Solution
 
tjgquickenAuthor Commented:
Addendum: This page from Adobe labs confirms that the <ul> tag (presumably all block level tags) must have a width in order to be centered.
http://labs.adobe.com/technologies/spry/samples/menubar/CenteringHorizontalMenuBarSample.html#centeringmenubar
0
 
tjgquickenAuthor Commented:
I meant that <div> tag above...

Unfortunately, that doesn't solve the problem. If the bounding box for the <div> element is larger than the bounding box for the <ul> element, then the <ul> is floated to the left of the <div> and not centered.
0
 
Mark StegglesWeb DeveloperCommented:
Hello tjgquicken,

Here is a way to center a floated menu of unknown width http://www.cssplay.co.uk/menus/centered.html

Here is a horizontal menu without using floats http://www.cssplay.co.uk/menus/centered2.html

Regards,

Steggs
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now