itsmikem
itsmikem

Reputation: 2168

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

Upvotes: 1

Views: 523

Answers (2)

Marcelo
Marcelo

Reputation: 4425

Based on your desired effect, you can use the first-child, last-child, nth-child, etc CSS selectors to control which elements get styled.

Here is a quick example using first-child:

.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: "";
}
<ol class="li_var">                             
   <li>quick brown fox</li>   
   <li>jumped over</li>
   <li>the lazy dog</li>
</ol>

And here is an example using nth-child:

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

Upvotes: 2

Josh Crozier
Josh Crozier

Reputation: 240948

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>

Upvotes: 2

Related Questions