← #26 Use template literal to concatenate strings
#27

Use negative nth-child and nth-last-child

Topics: CSS

nth-child is used to choose a child or a range of children of a given element.
Using negative nth-child will pick the first few children.

In the following example, the first three items will be underlined. The range of second to fifth items have the blue color.

li:nth-child(-n+3) {
text-decoration: underline;
}
li:nth-child(n+2):nth-child(-n+5) {
color: #2563EB;
}

In a similar way, nagative nth-last-child will pick the last few children.

/* Add a decorative line to the last two items */
li:nth-last-child(-n+2) {
text-decoration-line: line-through;
}

Demo

  • First
  • Second
  • Third
  • Fourth
  • Fifth
  • Sixth
  • Seventh

More

Fix a typo or suggest an improvement
#28 Set content for an empty link