css 如何让有序列表保持数字左对齐而不是右对齐?

4sup72z8  于 2023-04-01  发布在  其他
关注(0)|答案(2)|浏览(180)

我如何使一个有序列表像这样工作,其中的数字是左对齐的(所以它不会扰乱我的布局)?

1. hello
2. x
...
9. x
10. I am left aligned.
...
99. x
100. I am left aligned.

而不是这样(右对齐,默认值):

1. hello
    2. x
    ...
    9. x
   10. I am right aligned.
   ...
   99. x
  100. I am right aligned.
liwlm1x9

liwlm1x91#

我看到了很多复杂的答案,而解决方案却很简单:

ol {
 list-style-position: inside; /* this is what you need*/
 
 padding: 0;
}
<ol>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
</ol>
ee7vknir

ee7vknir2#

CSS counters可能是一个不错的选择,support可以一直追溯到IE 8:

/* Just to generate all the elements we need */

const ol = document.querySelector('ol');

for (let i = 1; i < 10001; i++) {
  const li = document.createElement('li');
  if (Math.log10(i) % 1) {
    li.textContent = 'x';
  } else {
    li.textContent = 'Left-aligned.'
  }
  ol.appendChild(li);
}
ol {
  counter-reset: list;
  list-style: none;
}

li {
  counter-increment: list;
}

li::before {
  content: counter(list) '. ';
}

/* Demo only */
ol {
  overflow: auto;
  max-height: 300px;
}
<ol>
</ol>

相关问题