Home >Web Front-end >CSS Tutorial >How to Perfectly Center a Horizontal `` Menu and its List Items?

How to Perfectly Center a Horizontal `` Menu and its List Items?

Susan Sarandon
Susan SarandonOriginal
2024-12-13 15:06:15217browse

How to Perfectly Center a Horizontal `` Menu and its List Items?

Centering a Horizontal

    Menu

    Problem:

    A horizontal menu consisting of an unordered list (

      ) needs to be centered within a container <div>. While attempts to center the
        within the <div> have been successful, the individual list items (
      • ) remain left-aligned within the
          .

          Solution:

          To achieve perfect centering of both the

            and its list items, the following approach is recommended:

            1. Float Wrapper: Create a float-left wrapper around the
                and set its position to "relative" with a negative left offset. This positions the wrapper off-screen to the left.
              • Reverse Nested Element: Position the inner
                  within the wrapper using "position: relative" and a positive left offset of 50%. This places the
                    exactly at the center of the wrapper.
                  • Float List Items: Adjust the
                  • elements to float left within the
                      and maintain their position within the
                        using "position: relative."

            Code Example:

            #buttons {
              float: right;
              position: relative;
              left: -50%;
              text-align: left;
            }
            
            #buttons ul {
              list-style: none;
              position: relative;
              left: 50%;
            }
            
            #buttons li {
              float: left;
              position: relative;
            }

            HTML Example:

            <div>

            With this implementation, the menu will be perfectly centered, with the list items evenly distributed within the horizontal space.

            The above is the detailed content of How to Perfectly Center a Horizontal `` Menu and its List Items?. 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