CSS - 缩进列表项

问题描述 投票:7回答:2

有没有办法使用CSS缩进每个列表项?

所以正常的清单:

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

显示如下:

One
  Two
    Three
      Four
html css html-lists
2个回答
9
投票

在这里你可以使用带有透明边框的:before伪元素。您可以通过更改伪元素的宽度来变量列表项的缩进。除此之外,你可以更改列表标记,如果设置list-style: none;并设置colorcontent

EDIT:

删除了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>

以下一个更改复杂列表标记更复杂(删除display: block,由@dippas建议,但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>

4
投票

如果你有很多list-items,那么@Banzay给出的answer更干净,但如果你只有少数几个,你可以使用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>
© www.soinside.com 2019 - 2024. All rights reserved.