Home  >  Article  >  Web Front-end  >  How to Center an Unordered List of Unknown Width in CSS?

How to Center an Unordered List of Unknown Width in CSS?

Susan Sarandon
Susan SarandonOriginal
2024-10-31 00:37:29164browse

How to Center an Unordered List of Unknown Width in CSS?

Centering an Unordered List of Unknown Width

In web design, it's common to have an unordered list of links in a footer for easy navigation. However, if the width of the list is unknown, it can be challenging to horizontally center the list items.

One solution for lists where the items can be displayed inline is:

<code class="css">#footer { text-align: center; }
#footer ul { list-style: none; }
#footer ul li { display: inline; }</code>

This applies text alignment center to the footer, removes the default list styling, and sets the list items to be displayed as inline elements.

However, in cases where list items must be displayed as blocks, the following CSS code can be used:

<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 approach sets the footer to full width and hides any overflow. The unordered list is positioned absolutely, floated to the left, and then shifted 50% to the left. The list items are also positioned absolutely, floated to the left, and shifted 50% to the right. This effectively centers the unordered list horizontally, regardless of its width.

The above is the detailed content of How to Center an Unordered List of Unknown Width in CSS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn