Centering a Horizontal Spry Menu Bar
A horizontal Spry Menu Bar is created from a series of nested unordered lists, styled with CSS to make each link a clickable block. The top-level menu items are floated left. When items are floated, they move as far as possible in the direction of the float. As a result, the menu bar is always positioned on the left.
The way to centre an element with CSS is to set the left and right margins to
auto. However, for this to work, the element must have a declared width. Wrapping the menu bar in a
<div> and setting its
margin property to
0 auto leaves the menu firmly on the left of the page—unless you also give the
<div> a width.
In fact, there's no need to use a
<div> at all. You can make all the necessary changes to the menu bar's existing style rules.
Editing the style sheet
The style rule that controls the position of a horizontal Spry Menu Bar is the first one in the style sheet. It looks like this:
Notice that the
margin property is set to
0. That zeroes the margin on all four sides. To centre the menu, change the
margin property like this:
margin: 0 auto;
On its own, that won't centre the menu, because the
width property is set to
auto. You need to change auto to the actual width of your menu bar. By default, a Spry Menu Bar contains four top-level items, and sets their width (in the
ul.MenuBarHorizontal li style rule) to
So, to centre a default Spry Menu Bar, you need to change the
width property in the
ul.MenuBarHorizontal style rule to
32em. With both changes, the style rule looks like this:
margin: 0 auto;
width: 32em; /* Change to the width of your own menu bar */
This centres a default horizontal Spry Menu Bar. Of course, you will probably want more menu items and to set your own width. Follow the instructions in the tutorial on customizing a Spry Menu Bar to learn how to do that. But remember, the key to centering a horizontal Spry Menu Bar is to give it a width. If you remove the width, you cannot centre the menu bar.
Note: Making the changes described here affects all horizontal menu bars attached to the same style sheet.