CSS - 缩进列表项

7

CSS有没有一种方法可以缩进每个列表项?

例如,一个普通的列表:

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
</ul>

展示效果如下:
One
  Two
    Three
      Four

3
使用带有递增值的nth-child选择器可能会有所帮助,但这似乎是一种过于臃肿的方法。使用Sass/Less循环可以减少需要编写的代码量,但最终的CSS(编译后)仍然会很大。 - Harry
2个回答

9
这里可以使用带有透明边框的 :before 伪元素来完成。您可以通过更改伪元素的宽度来变化列表项的缩进。同时,如果设置了 list-style: none; ,则可以更改列表标记,并设置 contentcolor
编辑: 移除 display: blockcolor: transparent,并使用空格字符 \00a0 作为内容。

li:before {
    float: left;
    content: "\00a0";
    width: 20px;
    border: 1px solid transparent;
}
<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
</ul>

下面这个稍微复杂一些,使用了不同的列表标记(根据@dippas的建议删除了display: block,但出于某种原因,使用border-top替代border无法正常工作)

ul {
   list-style: none;
   counter-reset: cnt;
}

li:before {
   float: left;
   counter-increment: cnt;
   content: counter(cnt)" \25b6";
   max-height: 100%;
   width: 29px;
   border: 1px solid transparent;
   margin-top: -.1em;
   color: green;
}
<ul>
      <li>One</li>
      <li>Two</li>
      <li>Three</li>
      <li>Four</li>
    </ul>


1
真是聪明啊 - Lee
这是一个不错的技巧,但可以改进,只需要使用 border-top 而不需要 display:block - dippas
@dippas 根据您的笔记,我已添加了另一种变体。 - Banzay
@Banzay 在火狐浏览器中可以运行,不知道你在使用哪个浏览器。 - dippas

4

如果您有大量的list-items,那么@Banzay给出的答案更加简洁,但如果只有少量的list-items,则可以使用nth-child来解决

li:first-child {
  margin-left: 10px
}
li:nth-child(2) {
  margin-left: 20px
}
li:nth-child(3) {
  margin-left: 30px
}
li:nth-child(4) {
  margin-left: 40px
}
/*just demo*/

ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
</ul>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接