0

I have following list:

<ul>
  <li class="parent">1.</li>
  <li class="child">1. first</li>
  <li class="child">1. second</li>
  <li class="child">1. third</li>

  <li class="parent">2.</li>
  <li class="child">2. first</li>
  <li class="child">2. second</li>
  <li class="child">2. third</li>
  <li class="child">2. fourth</li>
  <li class="child">2. fifth</li>

  <li class="parent">3.</li>
  <li class="child">3. first</li>
  <li class="child">3. second</li>
  <li class="child">3. third</li>
  <li class="child">3. fourth</li>

  <li class="parent">4.</li>
  <li class="child">4. first</li>
  <li class="child">4. second</li>
  <li class="child">4. third</li>
</ul>

I want to set specified background for first and last elements. While I have no problem with the first:

.parent + .child {
  background-color: whitesmoke;
}

then I do not know what to do with the lasts.

Simply: I want to match .child before .parent.

hsz
  • 148,279
  • 62
  • 259
  • 315

4 Answers4

2
li:nth-child(2n+2) {
  background-color: whitesmoke;
}

You are looking for the nth-child selector. http://jsfiddle.net/mKH7j/

schnawel007
  • 3,982
  • 3
  • 19
  • 27
  • Sorry, I had to modify my question. I need to match `1. third`, `2. fifth`, `3. fourth`, `4. third` – hsz Nov 15 '13 at 08:01
  • I would use `$('.parent').prev().css('background-color','red'); $('ul li').last().css('background-color','red');` http://jsfiddle.net/mKH7j/1/ – schnawel007 Nov 15 '13 at 08:07
1

You could use the jquery .prev() selector:

$('.parent').prev().css( "background-color", "red" );

http://jsfiddle.net/gC53q/1/

There is no previous-child selector in CSS. See here

Community
  • 1
  • 1
Michael Peterson
  • 1,123
  • 6
  • 14
0

You want the third of the three child selectors, so select the third sibling:

.child + .child + .child { background-color: red; }

http://jsfiddle.net/gC53q/

Michael Peterson
  • 1,123
  • 6
  • 14
  • Sorry, I had to modify my question. I need to match `1. third`, `2. fifth`, `3. fourth`, `4. third` – hsz Nov 15 '13 at 08:02
0

Here is one without jquery:

li:nth-child(2n) { background: red; }
li:nth-child(4n) { background: whitesmoke; }

And here is a demo: http://jsfiddle.net/G8vCZ/1/

Marius Djerv
  • 267
  • 1
  • 4
  • 18