Home > Software design >  How to have a ordered list with text indent for multi-line items
How to have a ordered list with text indent for multi-line items

Time:12-11

I'm trying to create an ordered list with the second line of <p> at the same indent as the first one.

However, that doesn't seem to work with the display: inline property. But if I remove the display: inline;, the ::before item and p are not on the same line.

How can I have the ::before and the p on the same line with the correct text indent?

--

With display: inline;: Result of display inline

Without display: inline;: Result of no display inline

Here's my code.

ol {
  counter-reset: item;
  list-style: none;
  list-style-position: outside;
  padding: 0;
  margin: 0;
}

ol li::before {
  counter-increment: item;
  content: counter(item) ".";
  padding-right: 24px;
  display: inline;
}

ol p {
  display: inline;
}
<ol>
  <li>
    <p>Text</p>
  </li>
  <li>
    <p>Text</p>
  </li>
  <li>
    <p>Text</p>
  </li>
  <li>
    <p>Text</p>
  </li>
</ol>

CodePudding user response:

One way would be to position the counter absolute within the li and give the before pseudo element and the p elements the same top margin (browsers may set this, this snippet sets it to 1em).

ol {
  counter-reset: item;
  list-style: none;
  list-style-position: outside;
  padding: 0;
  margin: 0;
}

ol li {
  position: relative;
}

ol li::before {
  counter-increment: item;
  content: counter(item) ".";
  position: absolute;
  margin-top: 1em;
}

ol li p {
  display: inline-block;
  padding-left: 24px;
  margin-top: 1em;
}
<ol>
  <li>
    <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text
      Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text </p>
  </li>
  <li>
    <p>Text</p>
  </li>
  <li>
    <p>Text</p>
  </li>
  <li>
    <p>Text</p>
  </li>
</ol>

CodePudding user response:

ol {
  counter-reset: item;
  list-style: none;
  list-style-position: outside;
  padding: 0;
  margin: 0;
}

ol li::before {
  counter-increment: item;
  content: counter(item) ".";
  padding-right: 24px;
  display: inline;
}

ol p {
  display: inline;
  text-indent: 24px;
}

This will indent the text in the p elements by 24 pixels, matching the distance between the ::before element and the start of the p element's text. This will give you the desired layout, with the ::before and p elements on the same line and the text of the p elements indented to match the ::before elements.

Note that you do not need to remove the display: inline; property in order to achieve this layout. You can leave this property as-is, and the text-indent property will still work as expected.

  • Related