Home > Web Front-end > CSS Tutorial > How to Center a List Horizontally Within a Div?

How to Center a List Horizontally Within a Div?

Mary-Kate Olsen
Release: 2024-12-04 22:04:15
Original
635 people have browsed it

How to Center a List Horizontally Within a Div?

How to Center a List within a Div

It is often desirable to center a list of items within a fixed-width div. This can be achieved through a combination of HTML and CSS techniques.

Solution:

To center the list and its child elements, we employ the following steps:

  1. Wrap the list in a div with text-align: center;.
  2. Set display: inline-block; on the list to center it within the div.
  3. Set appropriate margins and padding on the list and its elements to achieve the desired spacing.

Code:

<div class="wrapper">
    <ul>
        <li>List Item 1</li>
        <li>List Item 2</li>
        <li>List Item 3</li>
    </ul>
</div>
Copy after login
.wrapper {
    text-align: center;
}

.wrapper ul {
    display: inline-block;
    margin: 0;
    padding: 0;
}

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

Explanation:

  • The wrapper div centers the list horizontally.
  • The inline-block display on the list positions it within the div horizontally as well.
  • The margins and padding on the list and list items adjust the spacing and appearance of the elements.

By following these steps, you can effectively center a list within a div, ensuring a balanced and visually appealing layout.

The above is the detailed content of How to Center a List Horizontally Within a Div?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template