CSS Trick: How to target all elements besides the first

Posted on: Wed, 01/09/2019 - 04:39 By: admin

This CSS trick is quite simple. Let's say you have:

<ul>
  <li> list item </li>
  <li> list item </li>
  <li> list item </li>
</ul>

If you want to target the first <li>, you can do it as follows:

ul li { background-color: #FFFFFF; /* applies to every li */ }

div ul li:first-child { background-color: blue; /* targets only the first li */ }

This works in all major browsers.

For :first-child to work in IE8 and earlier, a <!DOCTYPE> must be declared.

English