• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1362
  • 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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

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