如何使用CSS计数器编写CSS选择器以将格式应用于特定元素?

时间:2012-05-15 19:10:16

标签: html css css-selectors

我正在使用CSS计数器和嵌套OL在HTML / CSS中创建目录,这非常有用。现在,我想在顶级OL上设置一个类“toc”(因为页面上有更多的OL而不仅仅是目录)。

如何调整CSS选择器以使计数器样式仅适用于<ol class="toc">

如果从第一个OL中删除class =“toc”,你会看到项目编号按照你的预期嵌套...当你添加toc类时,它都会进入底池。如何修复css选择器以使嵌套项目编号按预期工作?

<style>
ol {
  counter-reset: section;                /* Creates a new instance of the
                                            section counter with each ol
                                            element */
  list-style-type: none;
  text-decoration:underline;
}
li:before {
  counter-increment: section;            /* Increments only this instance
                                            of the section counter */
  content: counters(section, ".") " ";   /* Adds the value of all instances
                                            of the section counter separated
                                            by a ".". */
  font-weight:bold;
}
</style>​


<ol class="toc">

    <li>item
    <ol>
        <li>item
        <li>item
            <ol>
                <li>item
                <li>item
                <li>item
                <li>item
                <li>item
            </ol>
        </li>
        <li>item
    </ol>
</li>  
<li>item
    <ol>
        <li>item
        <li>item
        <li>item
        <li>item
    </ol>

</li> 
<li>item
    <ol>
        <li>item
        <li>item
        <li>item
        <li>item
        <li>item
        <li>item
    </ol>

</li> 
<li>item
    <ol>
        <li>item
            <ol>
                <li>item
                <li>item
                <li>item
            </ol>
        </li>

        <li>item
            <ol>
                <li>item
                <li>item</li>
                <li>item
                <li>item
                <li>item
                <li>item</li>
            </ol>
        </li>
        <li>item
            <ol>
                <li>item</li>
                <li>item</li>
            </ol>
    </ol>
</li> 
</ol>​

1 个答案:

答案 0 :(得分:0)

<style>
ol { color:black; }

ol.parentol { color:red; }

ol.childol { color:green; }

 /* nested ols with class of 'childol' 
  will not inherit the red font color */
</style>
<ol>
  <li>zzzzz</li>
  <li>
    <ol class="parentol">
      <li>aaaa</li>
      <li>
       <ol class="childol">
         <li>bbb</li>
       </ol>
      </li>
    </ol>
 </li>
</ol>