很简单,我希望有序列表像这样工作:
1. Foo
2. Bar
3a. Baz
3b. Qux
4. Etc...
Run Code Online (Sandbox Code Playgroud)
有没有办法在HTML中轻松地做这些事情?
鉴于以下加价:
<ol>
<li>Foo</li>
<li>
<ol>
<li>bar</li>
<li>baz</li>
</ol>
</li>
<li>Something else...</li>
</ol>?
Run Code Online (Sandbox Code Playgroud)
以下CSS 几乎可以工作:
ol {
counter-reset: topLevel;
}
li {
counter-increment: topLevel;
margin-left: 1em;
}
li::before {
content: counter(topLevel) '. ';
margin-right: 0.3em;
}
ol ol {
counter-reset: secondLevel;
}
ol ol li {
counter-increment: secondLevel;
}
ol ol li::before {
content: counter(topLevel) counter(secondLevel, lower-alpha) '. ';
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,唯一的问题是它包含topLevel对内部li元素的计数(如你所愿),还li包含对外部(包含那些内部元素)的计数,所以...还不完全存在.
并解决了上述问题!...在那些支持CSS :not()选择器的浏览器中:
ol {
counter-reset: topLevel;
}
li {
counter-increment: topLevel;
margin-left: 1em;
}
li:not(.hasChild)::before {
content: counter(topLevel) '. ';
margin-right: 0.3em;
}
ol ol {
counter-reset: secondLevel;
}
ol ol li {
counter-increment: secondLevel;
}
ol ol li::before,
ol li.hasChild ol li::before {
content: counter(topLevel) counter(secondLevel, lower-alpha) '. ';
}
Run Code Online (Sandbox Code Playgroud)
我忘了(最初)注意到为了这个工作(因为CSS没有父选择器(因为))我必须为li具有子ol元素的元素添加一个特定的类,以便适当地隐藏数字的重复.在这种情况下,我选择了类名.hasChild(可以在小提琴中看到).
顺便说一句,对li:not(.hasChild)::before规则的一个小改动允许右对齐的文本:
li:not(.hasChild)::before {
content: counter(topLevel) '. ';
width: 2em;
margin-right: 0.3em;
display: inline-block;
text-align: right;
}
Run Code Online (Sandbox Code Playgroud)