CSS有没有一种方法可以缩进每个列表项?
例如,一个普通的列表:
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>
展示效果如下:
One
Two
Three
Four
CSS有没有一种方法可以缩进每个列表项?
例如,一个普通的列表:
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>
One
Two
Three
Four
:before
伪元素来完成。您可以通过更改伪元素的宽度来变化列表项的缩进。同时,如果设置了 list-style: none;
,则可以更改列表标记,并设置 content
的 color
。display: block
和 color: 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>
border-top
而不需要 display:block
。 - dippas如果您有大量的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>
nth-child
选择器可能会有所帮助,但这似乎是一种过于臃肿的方法。使用Sass/Less循环可以减少需要编写的代码量,但最终的CSS(编译后)仍然会很大。 - Harry