Search code examples
htmlcsslayout

List bullets: is it possible to use (1) an attribute for the content while (2) preserving text alignment?


List bullets: is it possible to use (1) an attribute for the content while (2) preserving text alignment?

Goal:

       custom bullet text from attr : aligned list text
longer custom bullet text from attr : aligned list text

Attempt:

HTML:

<ul>
  <li data-bullet="custom bullet text from attr : "> aligned list text</li>
  <li data-bullet="longer custom bullet text from attr : "> aligned list text</li>
</ul>

CSS:

list-style-type: attr(data-label);

I can do (1) or (2), but not both:

I can get custom text without alignment

li::before {
  content: attr(data-bullet);
  margin-right: 5px;
}

li {
  list-style-type: none;
}
<ul>
  <li data-bullet="glorp"> text to align</li>
  <li data-bullet="glorpulous">text to align</li>
</ul>

Or aligned text, but only with a static list of predefined bullets

ol {
list-style-type: upper-roman;
}
<ol>
<li>aligned text</li>
<li>aligned text</li>
<li>aligned text</li>
<li>aligned text</li>
<li>aligned text</li>
<li>aligned text</li>
<li>aligned text</li>
</ol>

So, is there any way to have the bullet text come dynamically from an attribute in each individual <li> element, while keep the <li> text aligned?


Solution

  • You may use display:table and draw columns :

    li::before {
      content: attr(data-bullet)'.';
      display: table-cell;
      text-align: right;
    }
    
    li {
      list-style-type: none;
    }
    ul {
      display: table;
      border-spacing: 5px 0;
    }
    li {
      display: table-row;
    }
    <ul>
      <li data-bullet="glorp"> text to align</li>
      <li data-bullet="glorpulous">text to align</li>
    </ul>

    Else you will need to set a fixed width to the ::before .