Home >Web Front-end >CSS Tutorial >How to Center an Unordered List within a Fixed-Width Div?

How to Center an Unordered List within a Fixed-Width Div?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-02 22:50:151051browse

How to Center an Unordered List within a Fixed-Width Div?

Centering an Unordered List (
    ) with
  • Elements in a Fixed-Width Div

The scenario involves centering an unordered list (

    ) containing
  • elements within a div of fixed width. To achieve this, we will employ a combination of CSS and div elements.

    Solution

    1. Wrap the
        in a div with the class "wrapper".
      • Apply the following CSS styles to the "wrapper" class:

        .wrapper {
            text-align: center;
        }

        This centers the "wrapper" div and aligns the

          within it.

        • Apply the following CSS styles to the

            within the "wrapper" class:

            .wrapper ul {
                display: inline-block;
                margin: 0;
                padding: 0;
                /* IE support */
                zoom: 1;
                *display: inline;
            }

            This makes the

              behave like an inline element and allows it to expand dynamically based on its content.

            • Apply the following CSS styles to the

            • elements within the
                :

                .wrapper li {
                    float: left;
                    padding: 2px 5px;
                    border: 1px solid black;
                }

                This ensures that the

              • elements float inside the
                  and are aligned horizontally.

    Code Example

    <style>
        .wrapper {
            text-align: center;
        }
        .wrapper ul {
            display: inline-block;
            margin: 0;
            padding: 0;
            zoom: 1;
            *display: inline;
        }
        .wrapper li {
            float: left;
            padding: 2px 5px;
            border: 1px solid black;
        }
    </style>
    
    <div class="wrapper">
        <ul>
            <li>Element 1</li>
            <li>Element 2</li>
            <li>Element 3</li>
        </ul>
    </div>

    The above is the detailed content of How to Center an Unordered List within a Fixed-Width Div?. 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