How to Center an Unordered List Without a Parent Div in CSS?

Susan Sarandon
Release: 2024-10-30 12:33:25
Original
931 people have browsed it

How to Center an Unordered List Without a Parent Div in CSS?

How to Center an Unordered List Without a Parent DIV

In CSS, centering an unordered list (

    ) while maintaining left-aligned list items can be challenging without using a parent div. Here's how to achieve this effect:

    The provided code snippet, with a parent div, uses text-align: center on the div and display: inline-block on the ul to center the list. However, this method requires a parent div wrapper.

    To center an unordered list without a parent div, CSS properties like margin and text-align cannot be used effectively since the

      doesn't have a fixed width.

      The solution lies in setting the

        to behave like a table using display: table. This creates a table-like structure where rows are defined by list items (
      • ). By setting margin: 0 auto on the
          , the table (i.e., the list) is centered within its containing element.

          Here's the CSS code that achieves this effect:

          <code class="css">ul {
            display: table;
            margin: 0 auto;
          }</code>
          Copy after login

          To demonstrate, here's a code snippet that uses the provided HTML but without a parent div:

          <code class="html"><html>
          
          <body>
            <ul>
              <li>56456456</li>
              <li>4564564564564649999999999999999999999999999996</li>
              <li>45645</li>
            </ul>
          </body>
          
          </html></code>
          Copy after login

          This code will center the unordered list on the page, while still keeping the list items left aligned.

          The above is the detailed content of How to Center an Unordered List Without a Parent Div in CSS?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!