1

Is there a way in CSS to select an OL's LI based on the starting value, and not the nth-child.

Example:

<ol>
  <li></li>     // 1.
  <li></li>     // 2.
  <li></li>     // 3.
  <li></li>     // 4.
</ol>

<ol start="3">
  <li></li>     // 3.
  <li></li>     // 4.
</ol>

In the sample, the goal is to target the li with the value of 3 via CSS. In the top OL it would be the third one down, in the second OL it would be the first one since it starts at 3 already. I am avoiding using multiple nth child fixes, I am looking to see if it is possible with out it, by targeting the actual number of that LI.

Does anyone know if this is possible?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Paul Matos
  • 169
  • 1
  • 13
  • 2
    Not without JavaScript. CSS can't read the content of elements. At one point a `:contains` existed, but no more. – j08691 Feb 18 '16 at 16:58
  • @j08691: :contains wouldn't be of any use here, since there *is* no content to match by. A LI's ordinal value isn't part of its content unless it literally appears in the output. – BoltClock Feb 18 '16 at 18:15

1 Answers1

2

Unfortunately, CSS doesn't provide a selector that matches a list item by its ordinal value. It would certainly make a great addition to a future Selectors spec (I haven't seen anything like it proposed yet) assuming, for example, that browsers already have "list item" semantics built directly into HTML LI elements allowing them to take advantage of such a selector.

Neither does CSS provide the ability to parameterize selectors in a way that lets you write dynamic attribute or :nth-child() matches (see How can I use/emulate regex-like backreferences in attribute selectors?). The closest you can get is to have a preprocessor output as many static selectors as you need with the formula ol[start=$i] > li:nth-child($i). Here's an example in SCSS:

%item-3 {
  color: red;
}

ol:not([start]) > li:nth-child(3) {
  @extend %item-3;
}

// Assumes start attribute, if specified, begins with 2
@for $i from 2 through 3 {
  ol[start="#{$i}"] > li:nth-child(#{4 - $i}) {
    @extend %item-3;
  }
}

The hardest part, of course, is determining just how many of these you need.

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356