0

The code below appends the content before first-child of .current and .done

.current:first-child::before  {
 content: 'Current ';
    color: blue
}

.done:first-child::before {
 content: 'Done ';
    color: red
}
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<ul>
  <li class="current">The first li.</li>
  <li class="done">The second li.</li>
  <li class="done">The third li.</li>
</ul>

</body>
</html>

I am unable to understand why the content "Done" is not appended before "The second li" even though it is the first-child of .done (.done:first-child::before)

billy.farroll
  • 1,903
  • 2
  • 15
  • 23
Mayank Sharma
  • 29
  • 1
  • 1
  • 5

1 Answers1

1

Use :nth-child(n)

Learn about it:https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child

In your case you want only the first so use nth-child(2)

.current:first-child::before  {
 content: 'Current ';
    color: blue
}

.done:nth-child(2)::before {
 content: 'Done ';
    color: red
}
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<ul>
  <li class="current">The first li.</li>
  <li class="done">The second li.</li>
  <li class="done">The third li.</li>
</ul>

</body>
</html>

This will work also when multiple classes .current or .red are present.

.current > .current::before  {
 content: 'Current ';
  color: blue
}

.done > .done::before {
 content: 'Done ';
  color: red
}

ul li:not(.done):first-child::before {
  content: 'Current ';
  color: blue;
}

ul li:not(.done) + .done::before {
  content: 'Done';
  color: red;
}
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<ul>
  <li class="current">The first li.</li>
  <li class="current">The first li.</li>
  <li class="current">The first li.</li>
  <li class="done">The second li.</li>
  <li class="done">The third li.</li>
  <li class="done">The third li.</li>
  <li class="done">The third li.</li>
</ul>

</body>
</html>
Red
  • 6,599
  • 9
  • 43
  • 85
לבני מלכה
  • 15,925
  • 2
  • 23
  • 47
  • I edited my awnser into your awnser as I had a nice solution when they just closed it :| – Red Jun 07 '18 at 11:48
  • @Red nice one.... – לבני מלכה Jun 07 '18 at 11:49