<ol>,其中一些<li>具有伪元素,而其他<li>则不具有

时间:2015-11-20 19:36:05

标签: css pseudo-element css-counter

1. quick brown fox
<2. jumped over>
<3. the lazy dog>

我希望在一个<li>样式中使用<ol>::before伪元素(第2和第3项中的&lt;和&gt;)设置一些::after以上)。现在,我把它建成两个列表。我试图找到一种方法,只使用一个<ol>而不是两个,所以我可以避免使用counter-reset

.li_var {
  counter-reset: lt 1;
}
.li_var > li {
  counter-increment: lt;
}
.li_var > li::before {
  content: "<" counter(lt);
}
.li_var > li::after {
  content: ">";
}
<ol>
  <li>quick brown fox</li>
</ol>
<ol class="li_var">
  <li>jumped over</li>
  <li>the lazy dog</li>
</ol>

我的工作解决方案:

.li_var {
    list-style-type:none;
}
.li_var > li {
    counter-increment: lt;
}
.li_var > li:before {
    content: counter(lt) '. ';
}
.li_var li:nth-child(2), .li_var li:nth-child(3) {
     margin-left:-.6em;
}
.li_var li:nth-child(2):before, .li_var li:nth-child(3):before {
     content: '<' counter(lt) '. ';
}
.li_var li:nth-child(2):after, .li_var li:nth-child(3):after {
     content:'>';
}

2 个答案:

答案 0 :(得分:2)

您可以使用adjacent sibling combinator, +,以便选择前li个兄弟姐妹的li元素:

.li_var {
    padding-left: 0;
}
.li_var > li {
    counter-increment: lt;
}
.li_var > li:before {
    content: counter(lt) '. ';
}
.li_var > li + li:before {
    content: '<' counter(lt) '. ';
}
.li_var > li + li:after {
    content: '>';
}
<ol class="li_var">
  <li>quick brown fox</li>  
  <li>jumped over</li>
  <li>the lazy dog</li>
</ol>

答案 1 :(得分:2)

根据您所需的效果,您可以使用first-childlast-childnth-child等CSS选择器来控制要设置样式的元素。

以下是使用first-child的简短示例:

&#13;
&#13;
.li_var > li {
  counter-increment: lt;
}
.li_var > li::before {
  content: "<" counter(lt);
}
.li_var > li::after {
  content: ">";
}
.li_var > li:first-child::before {
  content: "";
}
.li_var > li:first-child::after {
  content: "";
}
&#13;
<ol class="li_var">                             
   <li>quick brown fox</li>   
   <li>jumped over</li>
   <li>the lazy dog</li>
</ol>
&#13;
&#13;
&#13;

以下是使用nth-child的示例:

&#13;
&#13;
.li_var > li {
  counter-increment: lt;
}
.li_var > li:nth-child(n+2)::before {
  content: "<";
}
.li_var > li:nth-child(n+2)::after {
  content: ">";
}
&#13;
    <ol class="li_var">                             
       <li>quick brown fox</li>   
       <li>jumped over</li>
       <li>the lazy dog</li>
    </ol>
&#13;
&#13;
&#13;