htmlcsshtml-lists

How to center an unordered list?


I need to center an unordered list of unknown width, while still keeping the list-items left aligned.

Achieve the same result as this:

HTML

<div>
    <ul>
        <li></li>
        <li></li>
        <li></li>
    </ul>
</div>

CSS

div { text-align: center; }
ul { display: inline-block; text-align: left; }

Except my <ul> doesn't have a parent div. ul { margin: 0 auto; } doesn't work because I don't have a fixed width. ul { text-align: center; } doesn't work because the list-items won't be left aligned anymore. So how can I center this <ul> while keeping the <li>s left aligned (without having a parent div wrapper)?

<ul>
    <li></li>
    <li></li>
    <li></li>
</ul>

EDIT: Perhaps my wording wasn't the best... The first block of code already works... what i need is to do it without the <div> wrapper, if that's possible of course. Float tricks? Pseudo element tricks? There must be a way.


Solution

  • ul {
      display: table;
      margin: 0 auto;
    }
    <html>
    
    <body>
      <ul>
        <li>56456456</li>
        <li>4564564564564649999999999999999999999999999996</li>
        <li>45645</li>
      </ul>
    </body>
    
    </html>