Horizontal Alignment of Unordered Lists with Unknown Width
In a website footer, it's common to have a list of links for navigation represented as an unordered list. To ensure horizontal centering regardless of list width, the conventional method of setting a fixed width on the UL element is often impractical.
Solution for Inline List Items
If the list items can be displayed inline, the solution is straightforward:
<code class="css">#footer { text-align: center; } #footer ul { list-style: none; } #footer ul li { display: inline; }</code>
However, when list items must be displayed as blocks, the following CSS proves effective:
<code class="css">#footer { width: 100%; overflow: hidden; } #footer ul { list-style: none; position: relative; float: left; display: block; left: 50%; } #footer ul li { position: relative; float: left; display: block; right: 50%; }</code>
This CSS positions the UL element at the center of the page and sets the LI elements to float around it, thereby achieving the desired horizontal alignment.
The above is the detailed content of How to Center an Unordered List Horizontally with Variable Width?. For more information, please follow other related articles on the PHP Chinese website!