HTML列表中的字母/数字组合是否可行?

时间:2012-09-07 20:56:34

标签: html html-lists

很简单,我希望有序列表能够像这样工作:

 1. Foo
 2. Bar
3a. Baz
3b. Qux
 4. Etc...

有没有办法在HTML中轻松地做这些事情?

2 个答案:

答案 0 :(得分:5)

鉴于以下加价:

<ol>
    <li>Foo</li>
    <li>
        <ol>
           <li>bar</li>
           <li>baz</li>
        </ol>
    </li>
    <li>Something else...</li>
</ol>​

以下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) '. ';
}

JS Fiddle demo

到目前为止,唯一的问题是它包含针对内部topLevel元素的li计数(如您所愿),还包含针对外部li的内容:not()(那些包含那些内在的元素),所以......还不完全存在。

以上问题解决了! ...在那些支持CSS 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) '. '; } 选择器的浏览器中:

li

JS Fiddle demo

我忘了(最初)要注意,为了这个工作(因为CSS没有父选择器(as yet),我不得不使用child {ol元素添加一个特定的类{1}}元素,以便适当地隐藏数字的重复。在这种情况下,我选择了类名.hasChild(可以在小提琴中看到)。

顺便说一句,li:not(.hasChild)::before规则的细微更改允许右对齐文字:

li:not(.hasChild)::before {
    content: counter(topLevel) '. ';
    width: 2em;
    margin-right: 0.3em;
    display: inline-block;
    text-align: right;
}

JS Fiddle demo

答案 1 :(得分:1)

它不能完全满足您的要求,并且需要对您的HTML进行一些(恼人的)更改,但我认为它与您将获得的一样接近。

http://jsfiddle.net/qGCUk/30/

<ol>
    <li>one</li>
    <li class="has_children">
        <ol>
           <li>two.one</li>
           <li>two.two</li>
           <li>two.three</li>
        </ol>
    </li>
</ol>

ol,li{
   padding:0;
   margin:0;    
}
ol { counter-reset: item }
li { display: block; padding-left: 0 }
li:before { 
    content: counters(item, ".") " "; 
    counter-increment: item 
}
LI.has_children:before { 
    content: " "; 
    counter-increment: item 
}

这只是数字,因为我认为你不能混合数字和字母。由于没有选择器和li包含和ol,因此您必须向具有子li的任何ol添加一个类。