Search code examples
csspseudo-elementcss-counter

<ol> with some <li>s having pseudo-elements and others not


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

I want to have some <li>s in a single <ol> styled with ::before and ::after pseudo-elements (the < and > in items 2 and 3 above). Right now, I have it built as two lists. I am trying to find a way to do that using just one <ol> rather than two, so I can avoid having to use 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>

my working solution:

.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:'>';
}

Solution

  • You could use the adjacent sibling combinator, +, in order to select the li elements with preceding li siblings:

    .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>