Search code examples
htmlcsstext-align

align unordered list items


I have unordered list:

-Item1-
-Item2Item2-
Item3Item3Item

Each element has different length. I want to create list in which all items had the same long background color with text aligned like:

-----------------
-----Item1-------
-----------------

-----------------
---Item2Item2----
-----------------

-----------------
-Item3Item3Item3-
-----------------

Here --- is colored background. How can I do it?


Solution

  • Setting the display of the ul to inline-block or block and setting the width to auto will make the items fit to the widest of the options.

    ul {
      width: auto;
      padding: 0;
      margin: 0;
      display: inline-block;
      float: left;
      clear: both;
    }
    li {
      background: lightblue;
      width: 100%;
      padding: 10px;
      text-align: center;
      list-style: none;
      margin-bottom: 10px;
    }
    <ul>
      <li>Item 1</li>
      <li>Item 2 Item 2</li>
    </ul>
    <ul>
      <li>Item 1</li>
      <li>Item 2 Item 2</li>
      <li>Item 3 Item 3 Item 3</li>
      <li>Item 4 Item 4 Item 4 Item 4</li>
    </ul>
    <ul>
      <li>Item 1</li>
      <li>Item 2 Item 2</li>
      <li>Item 3 Item 3 Item 3</li>
      <li>Item 4 Item 4 Item 4 Item 4</li>
      <li>Item 5 Item 5 Item 5</li>
      <li>Item 6 Item 6 Item 6 Item 6 Item 6</li>
    </ul>